-
Notifications
You must be signed in to change notification settings - Fork 0
/
album_search.py
378 lines (309 loc) · 10.5 KB
/
album_search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import spotipy
import os
import qrcode
import json
import urllib
import re
from zbarfunc import QRCODE_PATH
SPOTIPY = spotipy.Spotify()
def ms_to_hr(total_milliseconds):
"""
Returns a human readable with input in milliseconds
"""
minutes, milliseconds = divmod(total_milliseconds, 60000)
seconds = int(float(milliseconds) / 10000)
return "%02i:%02i" % (minutes, seconds)
def get_artist_albums(artist_uri):
"""
Returns a list of dictionaries, each dictionary contains the following entries:
'album_type'
'name'
'release_date'
'uri'
'image' this is a url of highest quality if available
'tracks' [] this is a list containing the following:
'name'
'track_number' (int)
'disk_number' (if available)
'duration'
'artists' [] this is a list containing the following:
'name'
'uri'
"""
albums_results = SPOTIPY.artist_albums(
artist_uri,
album_type='album', limit=50, country='CA'
)
albums_items = albums_results['items']
singles_results = SPOTIPY.artist_albums(
artist_uri,
album_type='single', limit=50, country='CA'
)
singles_items = singles_results['items']
while albums_results['next']:
albums_results = SPOTIPY.next(albums_results)
albums_items.extend(albums_results['items'])
while singles_results['next']:
singles_results = SPOTIPY.next(singles_results)
singles_items.extend(singles_results['items'])
albums = []
for album in albums_items:
try:
albums.append(
{
u'name': album['name'],
u'uri': album['uri'],
u'image': album['images'][0]['url'],
u'album_type' : album['album_type']
}
)
except IndexError:
albums.append(
{
u'name': album['name'],
u'uri': album['uri'],
u'album_type' : album['album_type']
}
)
for single in singles_items:
try:
albums.append(
{
u'name': single['name'],
u'uri': single['uri'],
u'image': single['images'][0]['url'],
u'album_type' : single['album_type']
}
)
except IndexError:
albums.append(
{
u'name': single['name'],
u'uri': single['uri'],
u'album_type' : single['album_type']
}
)
for album in albums:
searched_artist = SPOTIPY.artist(artist_uri)['name']
album[u'artists'] = [{u'name': searched_artist, u'uri': artist_uri}]
album = SPOTIPY.album(album['uri'])
album[u'release_date'] = album[u'release_date']
album[u'tracks'] = []
track_results = SPOTIPY.album(album['uri'])['tracks']
track_items = track_results['items']
while track_results['next']:
track_results = SPOTIPY.next(track_results)
track_items.extend(track_results['items'])
for track in track_items:
try:
album['tracks'].append(
{
u'name': track['name'],
u'track_number': track['track_number'],
u'duration' : track['duration_ms'],
u'disc_number': track['disc_number']
}
)
except KeyError:
album['tracks'].append(
{
u'name': track['name'],
u'track_number': track['track_number'],
u'duration': track['duration_ms'],
u'disc_number': 1
}
)
for artist in track['artists']:
if {
u'name': artist['name'],
u'uri': artist['uri']
} not in album[u'artists']:
album[u'artists'].append(
{
u'name': artist['name'],
u'uri': artist['uri']
}
)
return albums
def human_album(album):
"""
Takes the output of get_artist_albums[i] and prints info to disk
"""
artist = album['artists'][0]['name']
album_type = album['album_type']
album_name = album['name']
artist = re.sub('/', '-', artist)
album_type = re.sub('/', '-', album_type)
album_name = re.sub('/', '-', album_name)
location = (
QRCODE_PATH +
artist + '/'
+ album_type + '/' +
album_name
)
if os.path.isfile(location):
return album
to_print = []
total_duration = 0
try:
to_print.append(
'name: ' + album['name'] +
'\turi: ' + album['uri'] +
'\tdate: ' + album['release_date']
)
except KeyError:
to_print.append('name: ' + album['name'] + '\turi: ' + album['uri'])
for artist in album['artists']:
to_print.append('artist: ' + artist['name'] + '\turi: ' + artist['uri'])
try:
to_print.append('Album Art: ' + album['image'])
except KeyError:
to_print.append('No Album Art')
for track in album['tracks']:
duration = track['duration']
total_duration += duration
duration = ms_to_hr(duration)
to_print.append(
'Disk: ' + str(track['disk_number']) +
'\tTrack: ' + str(track['track_number']) +
'\tTrack Name: ' + track['name'] +
'\tDuration: ' + duration
)
total_duration = ms_to_hr(total_duration)
to_print.append(total_duration)
if not os.path.exists(os.path.dirname(location)):
os.makedirs(os.path.dirname(location))
with open(location.encode('utf-8'), 'w') as text_file:
for line in to_print:
text_file.write("%s\n" % line.encode('utf-8'))
return album
def create_qrcode(album):
"""
Takes the output of get_artist_albums[i] and creates a qr code
"""
artist = album['artists'][0]['name']
album_type = album['album_type']
album_name = album['name']
artist = re.sub('/', '-', artist)
album_type = re.sub('/', '-', album_type)
album_name = re.sub('/', '-', album_name)
location = QRCODE_PATH + artist + '/' + album_type + '/' + album_name
if os.path.isfile(location + '.png'):
return album
img = qrcode.make(album['uri'])
if not os.path.exists(os.path.dirname(location)):
os.makedirs(os.path.dirname(location))
img.save(location + '.png')
def save_json(album):
"""
Takes the output of get_artist_albums[i] and
saves the relevant data as a .json
"""
artist = album['artists'][0]['name']
album_type = album['album_type']
album_name = album['name']
artist = re.sub('/', '-', artist)
album_type = re.sub('/', '-', album_type)
album_name = re.sub('/', '-', album_name)
location = QRCODE_PATH + artist + '/' + album_type + '/' + album_name
if os.path.isfile(location + '.json'):
return album
if not os.path.exists(os.path.dirname(location)):
os.makedirs(os.path.dirname(location))
with open(location.encode('utf-8') + '.json', 'w') as text_file:
text_file.write(json.dumps(album))
def download_art(album):
"""
Takes the output of get_artist_albums[i] and saves the Album Art
"""
artist = album['artists'][0]['name']
album_type = album['album_type']
album_name = album['name']
artist = re.sub('/', '-', artist)
album_type = re.sub('/', '-', album_type)
album_name = re.sub('/', '-', album_name)
location = QRCODE_PATH + artist + '/' + album_type + '/' + album_name
if os.path.isfile(location + '.jpeg'):
return album
try:
urllib.urlretrieve(album['image'], location + '.jpeg')
except KeyError:
pass
def full_artists(albums):
"""
Takes the output of get_artist_albums and
saves a list of all artist mentioned
"""
artists = []
for album in albums:
for artist in album['artists']:
if artist not in artists:
artists.append(artist)
artist = artists[0]['name']
artist = re.sub('/', '-', artist)
location = QRCODE_PATH + artist + '/' + 'all_artists'
with open(location.encode('utf-8'), 'w') as text_file:
for line in artists:
text_file.write(
"name: %s\n\turi: %s\n\n" % (
line['name'].encode('utf-8'),
line['uri'].encode('utf-8')
)
)
def populate_folders(artist_uri):
"""
This function calls the other necessary
functions for creating and filling folders.
"""
print 'populating...'
albums = get_artist_albums(artist_uri)
print str(len(albums)) + ' entries to download.'
for album in albums:
human_album(album)
create_qrcode(album)
save_json(album)
download_art(album)
full_artists(albums)
print 'done'
def search_for_artist(search_term):
"""
This function takes a search term and returns the top result with a prompt.
It then calls the main populate_folders() function on the selected artist.
"""
results = SPOTIPY.search(search_term, type='artist')
artists = results['artists']['items']
results_index = 0
while True:
try:
print '\n' + search_term
print artists[results_index]['name'] + '\n'
prompt = raw_input(
'Is this what you were looking for?\n'
'[y] for yes [n] for next [x] '
'for new term or [q] to quit: '
)
#prompt= 'y'
if prompt.startswith('y'):
populate_folders(artists[results_index]['uri'])
break
elif prompt.startswith('x'):
break
elif prompt.startswith('q'):
return 0
elif prompt.startswith('n'):
results_index += 1
else:
break
except IndexError:
if results_index >= 1:
print 'No more results'
else:
print '\nNo results returned\n'
break
#composers = open('composers', 'rb').readlines()
#for composer in composers:
# search_for_artist(composer.strip())
def artist_search_loop():
while True:
if search_for_artist(raw_input("Enter a search query: ").strip()) == 0:
break