-
Notifications
You must be signed in to change notification settings - Fork 0
/
Smartify.py
165 lines (142 loc) · 5.55 KB
/
Smartify.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
__author__ = 'WisdomWolf'
from configparser import ConfigParser
import datetime
import itertools
import os
import pdb
import pylast
import spotipy
import spotipy.util as util
import sys
import time
if os.path.exists('settings.ini'):
config = ConfigParser()
config.read('settings.ini')
env = config['Environment Vars']
for k, v in env.items():
os.environ[k] = v
# PyLast
API_KEY = os.environ['LASTFM_API_KEY']
API_SECRET = os.environ['LASTFM_API_SECRET']
lastfm_username = os.environ['LASTFM_DEFAULT_USERNAME']
password_hash = os.environ['LASTFM_DEFAULT_PWHASH']
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET,
username=lastfm_username,
password_hash=password_hash)
# SpotiPy
scope = 'playlist-modify-public'
heard_songs = []
track_total = 0
def show_tracks(tracks, page=0):
for i, item in enumerate(tracks['items'], start=1):
track = item['track']
title = track['name']
artist = track['artists'][0]['name']
index = i + page + (page * 99)
count = get_user_play_count_in_track_info(artist, title)
info = '{0:<3}{1:>50} {2:<50} {3}'.format(index, artist, title, count)
print(info)
csv_info = '{0},"{1}","{2}",{3}\n'.format(index, artist, title, count)
# with open('playlist_counts.csv', 'a+') as playcount_file:
# print(index)
# playcount_file.write(csv_info)
def parse_tracks(tracks, page=0):
for i, item in enumerate(tracks['items'], start=1):
track = item['track']
pdb.set_trace()
artist = track['artists'][0]['name']
name = track['name']
track_id = track['id']
index = i + page + (page * 99)
play_count = get_user_play_count_in_track_info(artist, name)
if play_count > 0:
heard_songs.append(track_id)
update_progress(int(index / track_total * 100))
# print(name, '-', artist, '|', track_id, '|', play_count)
def get_user_play_count_in_track_info(artist, title):
# Arrange
track = pylast.Track(
artist=artist, title=title,
network=network, username=lastfm_username)
# Act
try:
count = track.get_userplaycount()
except WSError:
print('Unable to locate {0} - {1}'.format(artist, title))
return count
def display_playlists(playlists):
for playlist in playlists['items']:
if playlist['owner']['id'] == username:
print()
print(playlist['name'], '-', playlist['id'])
track_total = playlist['tracks']['total']
print(' total tracks', track_total)
def split_seq(iterable, size):
it = iter(iterable)
item = list(itertools.islice(it, size))
while item:
yield item
item = list(itertools.islice(it, size))
def update_progress(progress):
sys.stdout.write('\r[{0}] {1}%'.format('#'*int(progress/10), progress))
if __name__ == '__main__':
if len(sys.argv) > 1:
username = sys.argv[1]
else:
try:
username = os.environ['SPOTIFY_DEFAULT_USERNAME']
print('reading username from ini file')
except:
print("Usage: %s username" % (sys.argv[0],))
sys.exit()
username = username.lower()
token = util.prompt_for_user_token(username, scope)
if token:
pdb.set_trace()
sp = spotipy.Spotify(auth=token)
start_time = round(time.time())
playlists = sp.user_playlists(username)
playlist_id = '7N1WdCoTTSql2mN8OuaYfD'
playlist = sp.user_playlist(username, playlist_id)
track_total = playlist['tracks']['total']
print('Are you sure you want to filter {0}({1})'.format(
playlist['name'], track_total))
choice = input('-> ')
if choice.casefold() == 'yes' or choice.casefold() == 'y':
print(datetime.datetime.now())
print('Preparing to parse playlist...')
else:
print('Exiting...')
time.sleep(3)
sys.exit()
results = sp.user_playlist(username, playlist['id'], fields="tracks,next")
tracks = results['tracks']
parse_tracks(tracks)
page = 0
while tracks['next']:
page += 1
tracks = sp.next(tracks)
parse_tracks(tracks, page)
print('\nParsed {0} tracks.\nPreparing to remove {1} songs.'.format(
str(track_total), len(heard_songs)
))
if heard_songs:
split_lists = list(split_seq(heard_songs, 99))
for l in split_lists:
sp.user_playlist_remove_all_occurrences_of_tracks(username,
playlist_id, l)
end_time = round(time.time())
print('Completed. Duration: {0} Process Time: {1}'.format(
datetime.timedelta(seconds=(end_time - start_time)), time.process_time()))
pdb.set_trace()
# results = sp.user_playlist(username, playlist['id'], fields="tracks,next")
# tracks = results['tracks']
# show_tracks(tracks)
# page = 0
# while tracks['next']:
# page += 1
# tracks = sp.next(tracks)
# show_tracks(tracks, page)
# print('end of playlist:{0}'.format(playlist['name']))
else:
print("Can't get token for", username)