-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisthis.py
186 lines (152 loc) · 5.42 KB
/
isthis.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
import configparser
from dataclasses import dataclass
from typing import List, Tuple
import click
import spotipy
from rich.console import Console
from rich.table import Table
SEARCH_ARTIST_AMOUNT = 10
@dataclass
class Track:
name: str
uri: str
popularity: int
def authorize() -> Tuple[spotipy.Spotify, str, str]:
config = configparser.ConfigParser()
config.read("settings.conf")
username = config["spotify"]["username"]
market = config["spotify"]["market"]
scope = config["spotify"]["scope"]
client_id = config["spotify"]["client_id"]
client_secret = config["spotify"]["client_secret"]
redirect_uri = config["spotify"]["redirect_uri"]
token = spotipy.util.prompt_for_user_token(
username,
scope,
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
)
sp = spotipy.Spotify(auth=token)
return sp, username, market
def get_artist_tracks_uris(
sp: spotipy.Spotify, artist: str, market: str
) -> Tuple[str, List[str]]:
artist_albums = sp.artist_albums(artist, country=market, limit=50)
artist_name = get_artist_name(artist, artist_albums["items"])
print("Searching for tracks by", artist_name)
artist_tracks = []
for album in artist_albums["items"]:
albumtracks = sp.album_tracks(album["id"])
for track in albumtracks["items"]:
for trackartist in track["artists"]:
if trackartist["uri"] == artist:
artist_tracks.append(track["uri"])
print(f"Found {len(artist_tracks)} tracks")
return artist_name, artist_tracks
def get_artist_name(artist: str, artist_albums: List[dict]) -> str:
for album in artist_albums:
for a in album["artists"]:
if a["uri"] == artist:
return a["name"]
return "Unknown Artist"
def get_track_popularity(
sp: spotipy.Spotify, market: str, artist_tracks: list
) -> List[Track]:
sorted_tracks = []
i = 0
while i < len(artist_tracks):
tracks = sp.tracks(artist_tracks[i : 50 + i], market=market) # noqa: E203
for track in tracks["tracks"]:
t = Track(track["name"], track["uri"], track["popularity"])
sorted_tracks.append(t)
i += 50
sorted_tracks = sorted(
sorted_tracks, key=lambda track: track.popularity, reverse=True
)
return sorted_tracks
def create_playlist(
sp: spotipy.Spotify,
sorted_tracks: list,
artist_name: str,
username: str,
number_of_tracks: int,
) -> None:
track_uris = [sortedTrack.uri for sortedTrack in sorted_tracks]
tracks_to_add = track_uris[:number_of_tracks]
description = (
"This is playlist equivalent. Generated with https://github.com/noppaz/isthis"
)
pl = sp.user_playlist_create(
username, f"Is This {artist_name}", public=True, description=description
)
sp.user_playlist_add_tracks(username, pl["uri"], tracks_to_add)
print(f"Playlist created and {len(tracks_to_add)} songs added")
def search_artists(sp: spotipy.Spotify, query: str) -> list:
response: dict = sp.search(query, type="artist", limit=SEARCH_ARTIST_AMOUNT)
artists = sorted(
response["artists"]["items"],
key=lambda artist: artist["popularity"],
reverse=True,
)
console = Console()
table = Table(title="Artists")
table.add_column("", style="red", no_wrap=True)
table.add_column("Name", style="cyan", no_wrap=True)
table.add_column("Followers", style="cyan", no_wrap=True)
table.add_column("Genres", style="cyan", no_wrap=True)
table.add_column("URL", style="bright_black", no_wrap=True)
table.add_column("URI", style="bright_black", no_wrap=True)
for i, artist in enumerate(artists):
table.add_row(
str(i + 1),
artist["name"],
str(artist["followers"]["total"]),
", ".join(artist["genres"]),
artist["external_urls"]["spotify"],
artist["uri"],
)
console.print(table)
return artists
@click.group()
def cli():
pass
@cli.command(help="Create a playlist directly with the Artist URI")
@click.option(
"--artist",
prompt="Artist URI",
type=click.STRING,
help="Artist URI, example: spotify:artist:3WrFJ7ztbogyGnTHbHJFl2",
)
@click.option(
"--tracks",
default=30,
prompt="Number of tracks",
type=click.INT,
help="Number of tracks for playlist",
)
def create(artist: str, tracks: int) -> None:
sp, username, market = authorize()
artist_name, track_uris = get_artist_tracks_uris(sp, artist, market)
sorted_tracks = get_track_popularity(sp, market, track_uris)
create_playlist(sp, sorted_tracks, artist_name, username, tracks)
@cli.command(help="Interactive search for the artist")
def search() -> None:
sp, username, market = authorize()
query: str = click.prompt("Search", type=click.STRING)
artists = search_artists(sp, query)
artist_selection: int = click.prompt(
"Select artist",
type=click.IntRange(1, SEARCH_ARTIST_AMOUNT),
)
artist = artists[artist_selection - 1]["uri"]
artist_name, track_uris = get_artist_tracks_uris(sp, artist, market)
sorted_tracks = get_track_popularity(sp, market, track_uris)
tracks: int = click.prompt(
"Number of tracks for playlist",
default=30,
type=click.INT,
)
create_playlist(sp, sorted_tracks, artist_name, username, tracks)
if __name__ == "__main__":
cli()