Skip to content

Commit 5165b68

Browse files
committed
Clean up code
1 parent 26ebd84 commit 5165b68

File tree

3 files changed

+38
-30
lines changed

3 files changed

+38
-30
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,3 +131,4 @@ dmypy.json
131131
.cache-*
132132

133133
Failed matches - SpotifyMatcher.txt
134+
.vscode/

.vscode/settings.json

Lines changed: 0 additions & 3 deletions
This file was deleted.

main.py

Lines changed: 37 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -31,24 +31,35 @@ def connect_to_spotify():
3131
redirect_uri='https://open.spotify.com/',
3232
scope=scope,
3333
username=username)
34+
3435
if auth_manager:
3536
return (spotipy.Spotify(auth_manager=auth_manager), auth_manager)
37+
3638
print(f"Can't get token for {username}")
3739
sys.exit()
3840

3941

42+
def get_auth_token():
43+
auth_token = auth_manager.get_cached_token()
44+
45+
if auth_token:
46+
return auth_token
47+
48+
return auth_manager.get_access_token(as_dict=True)
49+
50+
4051
def get_title_and_artist(music_dir):
4152
"""Recursively reads local files in indicated music_dir and yields a string 'song - artist'"""
4253
if len(music_dir) == 0 or not os.path.isdir(music_dir):
4354
while True:
4455
music_dir = input("Please paste the path to your music directory:")
56+
4557
if os.path.isdir(music_dir):
4658
break
47-
else:
48-
print(
49-
"The provided path is not valid. Please try again or type "
50-
"in the path directly into the source code if there's "
51-
"issues\n(use Ctrl + C to exit the program)")
59+
60+
print("The provided path is not valid. Please try again or type "
61+
"in the path directly into the source code if there's "
62+
"issues\n(use Ctrl + C to exit the program)")
5263
else:
5364
print(f"Found valid path. Commencing search in {music_dir}")
5465

@@ -58,18 +69,20 @@ def get_title_and_artist(music_dir):
5869
try:
5970
audiofile = TinyTag.get(os.path.join(subdir, file))
6071
except:
61-
pass
62-
else:
63-
files_read += 1
64-
yield (f"track:{audiofile.title} artist:{audiofile.artist}", f"{audiofile.artist} - {audiofile.title}")
65-
# NOTE: Query being in double quotes makes it stick to the
66-
# given word order instead of matching a bunch of possibilities
67-
# Use it (by writing \" at the beginning and end of the string)
68-
# if you are not happy with the matches found
72+
continue
73+
74+
files_read += 1
75+
yield (f"track:{audiofile.title} artist:{audiofile.artist}", f"{audiofile.artist} - {audiofile.title}")
76+
# NOTE: Query being in double quotes makes it stick to the
77+
# given word order instead of matching a bunch of possibilities
78+
# Use it (by writing \" at the beginning and end of the string)
79+
# if you are not happy with the matches found
80+
6981
if files_read == 0:
7082
print("\nNo files found at the specified location."
7183
"Please check the path to the directory is correct.")
7284
sys.exit()
85+
7386
print(f"\nRead {files_read} files. Make sure to check for any possible "
7487
"unread files due to \"Lame tag CRC check failed\" or similar.\n"
7588
"Those come from an external library and this software cannot "
@@ -92,12 +105,12 @@ def create_new_playlist():
92105
try:
93106
date = datetime.now().strftime("%d %b %Y at %H:%M") # 1 Jan 2020 at 13:30
94107
playlist_id = sp.user_playlist_create(
95-
username, "SpotifyMatcher",
108+
username,
109+
"SpotifyMatcher",
96110
description="Playlist automatically created by SpotifyMatcher "
97111
f"from my local files on {date}. "
98112
"Try it at https://github.com/BoscoDomingo/SpotifyMatcher!")["id"]
99-
print(
100-
f"Find it at: https://open.spotify.com/playlist/{playlist_id}")
113+
print(f"Find it at: https://open.spotify.com/playlist/{playlist_id}")
101114
return playlist_id
102115
except:
103116
print("\nWARNING: \n"
@@ -111,25 +124,19 @@ def add_tracks_to_playlist(track_ids):
111124
spotify_limit = 100
112125
while len(track_ids) > 0:
113126
try:
114-
sp.user_playlist_add_tracks(
115-
username, playlist_id, track_ids[:spotify_limit])
127+
sp.user_playlist_add_tracks(username, playlist_id, track_ids[:spotify_limit])
116128
except: # API rate limit reached
117129
sleep(0.2)
118130
else:
119131
del track_ids[:spotify_limit]
120132

121133

122134
if __name__ == "__main__":
123-
"""
124-
TO-DO: Allow users to pick between 2 modes: direct like or create playlist
125-
direct_like_scope = 'user-library-modify'
126-
create_playlist_scope = 'playlist-modify-public'
127-
"""
128135
scope = 'playlist-modify-public user-library-modify'
129136
music_dir = ""
130137
# Write the dirpath directly here to avoid having to do it through terminal.
131138
# Make sure to escape backslashes. Examples:
132-
# '/Users/John/Music/My Music'
139+
# 'C:/Users/John/Music/My Music'
133140
# "C:\\Users\\John\\Music\\My Music"
134141

135142
username, playlist_id = get_user_data()
@@ -138,7 +145,7 @@ def add_tracks_to_playlist(track_ids):
138145
# Needed to get the cached authentication if missing
139146
dummy_search = sp.search("whatever", limit=1)
140147

141-
token_info = auth_manager.get_cached_token() if auth_manager.get_cached_token() else auth_manager.get_access_token(as_dict=True)
148+
token_info = get_auth_token()
142149
track_ids = []
143150
failed_song_names = []
144151
searched_songs = 0
@@ -148,17 +155,19 @@ def add_tracks_to_playlist(track_ids):
148155
for query_song_pair in get_title_and_artist(music_dir):
149156
if auth_manager.is_token_expired(token_info):
150157
token_info = auth_manager.refresh_access_token(token_info["refresh_token"])
158+
151159
searched_songs += 1
152160
print(f"{searched_songs}: {query_song_pair[1]}")
161+
153162
try:
154-
result = sp.search(query_song_pair[0], limit=1)[
155-
"tracks"]['items'][0]['id']
163+
result = sp.search(query_song_pair[0], limit=1)["tracks"]['items'][0]['id']
156164
except:
157165
print("\t*NO MATCH*")
158166
failed_matches_file.write(f"{query_song_pair[1]}\n")
159167
failed_song_names.append(query_song_pair[1])
160168
else:
161169
track_ids.append(result)
170+
162171
success_rate = "{:.2f}".format(len(track_ids)/(searched_songs-1)*100)
163172
print(
164173
f"\n***TOTAL SONGS SEARCHED: {searched_songs}"
@@ -167,6 +176,7 @@ def add_tracks_to_playlist(track_ids):
167176
playlist_id = ensure_playlist_exists(playlist_id)
168177
number_of_matches = len(track_ids)
169178
add_tracks_to_playlist(track_ids)
179+
170180
print(f"\nSuccessfully added {number_of_matches} songs to the playlist.\n"
171181
"Thank you for using SpotifyMatcher!")
172182
print(f"\n{searched_songs-number_of_matches} UNMATCHED SONGS (search "

0 commit comments

Comments
 (0)