Last active
December 22, 2015 17:18
-
-
Save nt/6505234 to your computer and use it in GitHub Desktop.
Building poems like those here: http://spotifypoetry.tumblr.com/
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
from httplib import HTTPConnection | |
import urllib | |
import json, sys | |
inp = sys.argv[1] | |
con = HTTPConnection("ws.spotify.com") | |
def tokenize(s): | |
return map(lambda l:l.lower(), s.split(" ")) | |
def try_terms(terms): | |
print "Trying terms " + str(terms) | |
params = urllib.quote(" ".join(terms)) | |
con.request("GET", "/search/1/track.json?q="+params) | |
resp = con.getresponse() | |
data = json.loads(resp.read()) | |
for a in data['tracks']: | |
if tokenize(a['name']) == terms: | |
return a | |
return None | |
tokens = tokenize(inp) | |
playlists = [] | |
def rec(terms, cur): | |
if len(terms)==0: | |
playlists.append(cur) | |
for i in range(1,len(terms)+1): | |
track = try_terms(terms[0:i]) | |
if track: | |
cur.append(track) | |
rec(terms[i:], cur[:]) | |
rec(tokens, []) | |
# Outputting the solution | |
for playlist in playlists: | |
print "Solution >" | |
for track in playlist: | |
print track | |
#print "http://open.spotify.com/track/%s" % track['track']['href'].split(":")[-1] |
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
from httplib import HTTPConnection | |
import urllib | |
import json, sys | |
inp = sys.argv[1] | |
max_length = 6 | |
con = HTTPConnection("ws.spotify.com") | |
def tokenize(s): | |
return map(lambda l:l.lower(), s.split(" ")) | |
def try_terms(terms): | |
print "Trying terms " + str(terms) | |
params = urllib.quote(" ".join(terms)) | |
con.request("GET", "/search/1/track.json?q="+params) | |
resp = con.getresponse() | |
data = json.loads(resp.read()) | |
for a in data['tracks']: | |
if tokenize(a['name']) == terms: | |
return a | |
return None | |
def find_longest(toks): | |
for i in range(1, max_length+1)[::-1]: | |
t = try_terms(toks[0:i]) | |
if t: | |
return { "terms" : toks[0:i], "track" : t, "length":i } | |
return None | |
tokens = tokenize(inp) | |
playlist = [] | |
while(len(tokens)>0): | |
l = find_longest(tokens) | |
if not l: | |
raise NameError("Need to implement backtracking") | |
playlist.append(l) | |
tokens = tokens[l["length"]:] | |
# Outputting the solution | |
for track in playlist: | |
print "http://open.spotify.com/track/%s" % track['track']['href'].split(":")[-1] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment