-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathspotify.py
More file actions
426 lines (363 loc) · 14.8 KB
/
Copy pathspotify.py
File metadata and controls
426 lines (363 loc) · 14.8 KB
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# Download spotify playlist to mp3
import tekore as tk
import os
import yt_dlp as youtube_dl
import eyed3
import urllib
import re
# import vlc
# Spotify API
client_id = 'YOUR_CLIENT_ID_HERE'
client_secret = 'YOUR_CLIENT_SECRET_HERE'
redirect_uri = 'http://localhost:5000/'
user_token = None
# Read user_token from file if it exists
if os.path.exists('user_token.txt'):
with open('user_token.txt', 'r') as f:
user_token = f.read()
# Test token if it is valid
try:
spotify = tk.Spotify(user_token)
spotify.current_user()
except tk.HTTPError:
# If token is invalid, get new token
user_token = tk.prompt_for_user_token(
client_id,
client_secret,
redirect_uri,
scope=tk.scope.every
)
# Save user_token in a file
with open('user_token.txt', 'w') as f:
f.write(str(user_token))
spotify = tk.Spotify(user_token)
class MyLogger(object):
def debug(self, msg):
pass
def warning(self, msg):
pass
def error(self, msg):
print(msg)
def my_hook(d):
if d['status'] == 'finished':
print('Done downloading, now converting ...')
ydl_opts = {
# If you use windows make sure to use \\ instead of \.
# It should look something like this 'C:\\ffmpeg\\bin\\ffmpeg.exe'
'ffmpeg_location': 'YOUR_FFMEG_LOCATION_HERE',
'format': 'bestaudio/best',
'extractaudio': True,
'outtmpl': '%(title)s.%(ext)s',
'addmetadata': True,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '320',
}],
'logger': MyLogger(),
# 'progress_hooks': [my_hook],
}
def get_yt_track_url(track):
# Get youtube url of song
song = track.name
artist = track.artists[0].name
print('Searching: ' + song + ' by ' + artist)
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
try:
result = ydl.extract_info('ytsearch1:' + song + ' ' + artist, download=False)['entries'][0]
return result['webpage_url']
except:
return None
def sanitize_filename(name: str) -> str:
"""
Remove or replace characters that are not allowed in filenames.
"""
# Replace invalid characters with underscore
sanitized = re.sub(r'[<>:"/\\|?*]', '_', name)
# Strip trailing/leading spaces and dots (Windows doesn’t like them)
sanitized = sanitized.strip().rstrip('.')
return sanitized
def songs_downloader(base_folder, tracks):
"""
Save as: <base or none>/<Artist>/<Album>/<NN - Song>.mp3
Prevents duplicates when base == album (e.g., 'Album/Artist/Album/Song').
"""
for i, track in enumerate(tracks):
print(f"Tracks processed: {i}/{len(tracks)}")
# Raw fields from Spotify (with safe fallbacks)
raw_song = getattr(track, "name", None) or "Unknown Title"
raw_artist = (track.artists[0].name if getattr(track, "artists", None) else "Unknown Artist")
raw_album = (track.album.name if getattr(track, "album", None) else "Unknown Album")
# Sanitize for filesystem
song = sanitize_filename(raw_song)
artist = sanitize_filename(raw_artist)
album = sanitize_filename(raw_album)
# Filename (with track number if present)
track_num = getattr(track, "track_number", None)
file_name = f"{track_num:02d} - {song}.mp3" if isinstance(track_num, int) and track_num > 0 else f"{song}.mp3"
# Base folder handling (avoid Album/Artist/Album nesting)
base = sanitize_filename(base_folder) if base_folder else ""
if base and base.lower() == album.lower():
base = "" # prevent duplicate album segment
# Build final destination: <base>/<Artist>/<Album>/
parts = [p for p in [base, artist, album] if p]
destination_path = os.path.join(*parts) if parts else os.path.join(artist, album)
full_destination = os.path.join(destination_path, file_name)
# Skip if already there
if os.path.exists(full_destination):
print(f"Already downloaded: {full_destination}")
continue
# Ensure folder exists
os.makedirs(destination_path, exist_ok=True)
# yt-dlp options per-track so we don't mutate globals
ydl_local = dict(ydl_opts)
ydl_local['outtmpl'] = os.path.join(destination_path, os.path.splitext(file_name)[0] + ".%(ext)s")
print(f"Downloading: {raw_song} by {raw_artist}")
try:
with youtube_dl.YoutubeDL(ydl_local) as ydl:
ydl.download([f'ytsearch1:{raw_song} {raw_artist}'])
# If postprocessor altered the name, normalize to our intended filename
if not os.path.exists(full_destination):
mp3s = [f for f in os.listdir(destination_path) if f.lower().endswith('.mp3')]
if mp3s:
newest = max((os.path.join(destination_path, f) for f in mp3s), key=os.path.getmtime)
if newest != full_destination:
try:
os.rename(newest, full_destination)
except Exception as e:
print(f"Warning: couldn't rename {newest} -> {full_destination}: {e}")
# Tagging
if os.path.exists(full_destination):
audiofile = eyed3.load(full_destination)
if audiofile is None:
print(f"Warning: couldn't load mp3 for tagging: {full_destination}")
continue
if audiofile.tag is None:
audiofile.initTag()
audiofile.tag.artist = raw_artist
audiofile.tag.title = raw_song
audiofile.tag.album = raw_album
if getattr(track, "album", None) and getattr(track.album, "artists", None):
audiofile.tag.album_artist = track.album.artists[0].name
# Genre from Spotify artist
try:
artist_id = track.artists[0].id
genres = spotify.artist(artist_id).genres
if genres:
audiofile.tag.genre = genres[-1]
except Exception:
pass
if isinstance(track_num, int) and track_num > 0:
audiofile.tag.track_num = track_num
# Album art
try:
if getattr(track, "album", None) and getattr(track.album, "images", None):
imagedata = urllib.request.urlopen(track.album.images[0].url).read()
audiofile.tag.images.set(3, imagedata, 'image/jpeg')
except Exception as e:
print(f"Warning: couldn't embed cover art: {e}")
audiofile.tag.save()
print(f"Saved: {full_destination}")
else:
print(f"Failed to find the downloaded file at: {full_destination}")
except youtube_dl.utils.DownloadError as e:
print(f"Error downloading '{raw_song}' by '{raw_artist}': {e}. Skipping.")
continue
except Exception as e:
print(f"Unexpected error for '{raw_song}' by '{raw_artist}': {e}. Skipping.")
continue
print("Logged in as " + spotify.current_user().email)
def choose_quality():
# Choose quality of songs
quality = input("Choose quality of songs (190 or 320): ")
if quality == '':
ydl_opts['postprocessors'][0]['preferredquality'] = '320'
elif quality == '190':
ydl_opts['postprocessors'][0]['preferredquality'] = '190'
elif quality == '320':
ydl_opts['postprocessors'][0]['preferredquality'] = '320'
else:
print("Invalid input")
choose_quality()
def list_playlists():
playlists = spotify.playlists(spotify.current_user().id)
for i, playlist in enumerate(playlists.items):
print(i, end=". ")
print(playlist.name)
return playlists
def get_playlist_tracks(playlist):
tracks = []
playlist_uri = playlist.uri.split(":")[-1]
results = spotify.playlist_items(playlist_uri)
tracks.extend(results.items)
while results.next:
results = spotify.next(results)
tracks.extend(results.items)
return tracks
def list_liked_songs():
liked_songs = []
results = spotify.saved_tracks()
liked_songs.extend(results.items)
while results.next:
results = spotify.next(results)
liked_songs.extend(results.items)
return liked_songs
def get_recommendations(tracks):
track_ids = [t.track.id for t in tracks]
recommendations = spotify.recommendations(track_ids=track_ids).tracks
return recommendations
def get_top_tracks(limit=5):
top_tracks = spotify.current_user_top_tracks(limit=limit).items
return top_tracks
def create_playlist(name, description):
user = spotify.current_user()
playlist = spotify.playlist_create(
user.id,
name,
public=False,
description=description
)
return playlist
def add_tracks_to_playlist(playlist, tracks):
uris = [t.uri for t in tracks]
spotify.playlist_add(playlist.id, uris=uris)
def menu():
print("1. Download songs from playlist")
print("2. Download songs from recommendations")
print("3. Download songs from top tracks")
print("4. Download songs from top tracks recommendations")
print("5. Create playlist from recommendations")
print("6. Create playlist from top tracks")
print("7. Create playlist from top tracks recommendations")
print("8. Search")
print("9. Exit")
print("Extra options:")
print("10. Choose quality of songs")
print("11. Download liked songs") # New option for downloading liked songs
return int(input("Enter option: "))
def playlist_tracks_to_tracks(playlist_tracks):
tracks = []
for playlist_track in playlist_tracks:
tracks.append(playlist_track.track)
return tracks
def search(query, types=('track', 'artist', 'album')):
results = spotify.search(query, types=types, limit=10)
return results
def search_tracks(query):
results = search(query, types=('track',))
return results
def search_artists(query):
results = search(query, types=('artist',))
return results
def search_albums(query):
results = search(query, types=('album',))
return results
def search_playlists(query):
results = search(query, types=('playlist',))
return results
def search_menu():
print("1. Search tracks")
print("2. Search artists")
print("3. Search albums")
print("4. Exit")
action = int(input("Enter option: "))
if action == 1:
query = input("Enter query: ")
results = search_tracks(query)
for i, track in enumerate(results[0].items):
print(i, end=". ")
print(track.name, end=" - ")
print(track.artists[0].name)
return query, results[0].items
elif action == 2:
query = input("Enter query: ")
results = search_artists(query)
for i, artist in enumerate(results[0].items):
print(i, end=". ")
print(artist.name)
return query, results[0].items
elif action == 3:
query = input("Enter query: ")
results = search_albums(query)
for i, album in enumerate(results[0].items):
print(i, end=". ")
print(album.name, end=" - ")
print(album.artists[0].name)
return query, results[0].items
elif action == 4:
return None
def post_search_menu(query, results):
print()
print("1. Download songs from search results")
print("2. Create playlist from search results")
print("3. Exit")
action = int(input("Enter option: "))
if action == 1:
# Choose song to download (one or more)
songs_index = input("Enter songs number, all for all: ")
if songs_index == 'all':
songs_downloader("Search : "+query, results)
else:
# Split could be a , a space , a . or a -
songs_index = songs_index.replace(',', ' ').replace('.', ' ').replace('-', ' ').split()
songs_index = [int(i) for i in songs_index]
songs_downloader("Search : "+query, [results[i] for i in songs_index])
elif action == 2:
playlist = create_playlist(query, "Created by spotify-downloader")
add_tracks_to_playlist(playlist, results)
print("Playlist created: " + playlist.name)
elif action == 3:
return
def main():
while True:
action = menu()
if action == 1:
playlists = list_playlists()
playlist = playlists.items[int(input("Enter playlist number: "))]
tracks = get_playlist_tracks(playlist)
tracks = playlist_tracks_to_tracks(tracks)
songs_downloader("Music", tracks)
elif action == 2:
playlists = list_playlists()
playlist = playlists.items[int(input("Enter playlist number: "))]
tracks = get_playlist_tracks(playlist)
recommendations = get_recommendations(tracks)
songs_downloader("Music", recommendations)
elif action == 3:
top_tracks = get_top_tracks(int(input("Enter number of top tracks: ")))
songs_downloader("Music", top_tracks)
elif action == 4:
top_tracks = get_top_tracks(int(input("Enter number of top tracks: ")))
recommendations = get_recommendations(top_tracks)
songs_downloader("Music", recommendations)
elif action == 5:
playlists = list_playlists()
playlist = playlists.items[int(input("Enter playlist number: "))]
tracks = get_playlist_tracks(playlist)
recommendations = get_recommendations(tracks)
playlist = create_playlist(playlist.name + " recommendations", "Recommended songs from " + playlist.name)
add_tracks_to_playlist(playlist, recommendations)
elif action == 6:
top_tracks = get_top_tracks()
playlist = create_playlist("Top tracks", "Top tracks from user")
add_tracks_to_playlist(playlist, top_tracks)
elif action == 7:
top_tracks = get_top_tracks()
recommendations = get_recommendations(top_tracks)
playlist = create_playlist("Top tracks recommendations", "Recommended songs from top tracks")
add_tracks_to_playlist(playlist, recommendations)
elif action == 8:
search, results = search_menu()
post_search_menu(search, results)
elif action == 9:
exit()
elif action == 10:
choose_quality()
elif action == 11: # New action for downloading liked songs
liked_songs = list_liked_songs()
liked_tracks = [item.track for item in liked_songs]
songs_downloader("Music", liked_tracks)
import time
import sys
if __name__ == "__main__":
main()