Skip to content

Instantly share code, notes, and snippets.

@sk89q
Created October 26, 2013 19:44
Show Gist options
  • Save sk89q/7173660 to your computer and use it in GitHub Desktop.
Save sk89q/7173660 to your computer and use it in GitHub Desktop.
Fetches the recent tracks of a last.fm user within a date range and converts it to a list of Spotify URLs (to be copied directly into the Spotify program) sorted descending by play count
#!/usr/bin/env python2.7
import requests
import datetime
import calendar
import time
import json
from pprint import pprint
def timestamp(dt):
return calendar.timegm(dt.utctimetuple())
def spotify_id(artist, name):
payload = {'q': artist + " - " + name}
data = requests\
.get("http://ws.spotify.com/search/1/track.json", params=payload)\
.json()
for track in data['tracks']:
if not 'karaoke' in track['name'].lower():
return track['href']
raise Exception("Failed to get Spotify ID")
def recent_tracks(name, start, end):
num = 1
page = 0
while page < num:
print("{}/{}: recent tracks".format(page + 1, num))
# HTTP API call
payload = {'method': 'user.getrecenttracks',
'user': name,
'api_key': lastfm_key,
'format': 'json',
'from': timestamp(start),
'to': timestamp(end),
'page': page}
response = requests\
.get("http://ws.audioscrobbler.com/2.0/", params=payload)\
.json()
# yield each track
if 'recenttracks' in response:
page += 1
data = response['recenttracks']
if '@attr' in data:
num = int(data['@attr']['totalPages'])
for track in data['track']:
try:
# test existence of these keys
track['artist']['#text']
track['name']
track['url']
yield track
except: pass
time.sleep(0.5)
else:
return # no tracks found
else:
print("Got invalid result {0}".format(response))
time.sleep(5)
def top_tracks(name, start, end):
tracks = {}
for track in recent_tracks(name, start, end):
url = track['url']
if url in tracks:
tracks[url]['count'] += 1
else:
stored = {'count': 1}
stored.update(track)
tracks[url] = stored
return sorted(tracks.values(), key=lambda r: -r['count'])
lastfm_key = 'CHANGE THIS'
user = 'CHANGE THIS'
start = datetime.datetime(2013, 1, 1)
length = datetime.timedelta(weeks=52)
end = start + length
for track in top_tracks(user, start=start, end=end):
count = track['count']
artist = track['artist']['#text']
title = track['name']
spotify_url = ""
try:
spotify_url = spotify_id(artist, title)\
.replace("spotify:track:", "http://open.spotify.com/track/")
except: pass
print("{: <55} [{}] {} - {}"\
.format(spotify_url, count, artist, title)).encode('utf-8')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment