Created
October 3, 2014 22:26
-
-
Save apassant/2ae720683b241bc5eaf0 to your computer and use it in GitHub Desktop.
Get an album stats (mood and tempo) using the Gracenote API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AlbumStats(object): | |
""" | |
Get stats (mood and tempo) about an album using the Gracenote API. | |
Requires: | |
1) A Gracenote API key - https://developer.gracenote.com/ | |
2) pygn - https://github.com/cweichen/pygn | |
Example: | |
the_best_album_ever = AlbumStats('London Calling', 'The Clash', my_client_ID, my_user_ID) | |
the_best_album_ever.get_stats() | |
print the_best_album_ever | |
Parameters | |
---------- | |
artist : string | |
The artist name | |
album : string | |
The album name | |
clientID : string | |
Your Gracenote Client ID | |
clientID : string | |
Your Gracenote User ID | |
""" | |
def __init__(self, artist, album, clientID, userID): | |
self.artist = artist | |
self.album = album | |
self.clientID = clientID | |
self.userID = userID | |
self.stats = { | |
'mood' : {}, | |
'tempo' : {} | |
} | |
self.num_tracks = 0 | |
def __str__(self): | |
"""Display stats about Mood and Tempo for the album""" | |
out = '{artist} - {album}\n'.format(**{ | |
'artist' : self.artist, | |
'album' : self.album, | |
}) | |
for (k, v) in self.stats.items(): | |
out += "# {key}\n".format(**{ | |
'key' : k.capitalize() | |
}) | |
for data in sorted(v.items(), key=lambda x: x[1], reverse=True)[:min(10, self.num_tracks)]: | |
out += "- {data}: {len} ({pc:.2f}%)\n".format(**{ | |
'data' : data[0], | |
'len' : data[1], | |
'pc' : data[1]/float(self.num_tracks)*100 | |
}) | |
return out | |
__repr__ = __str__ | |
def get_stats(self): | |
"""Fetch stats from the Gracenote API.""" | |
metadata = pygn.search(clientID=self.clientID, userID=self.userID, artist=self.artist, album=self.album) | |
tracks = metadata.get('tracks') | |
self.num_tracks = len(tracks) | |
for track in tracks: | |
print track | |
for (k, v) in self.stats.items(): | |
for x in track.get(k).values(): | |
v.setdefault(x['TEXT'], 0) | |
v[x['TEXT']] += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment