evolutionary-playlist-builder / src /spotipy_utils.py
carterwward
update gradio version
0e9a9df
Raw History Blame Contribute Delete
5.04 kB
import spotipy
import os
import gradio as gr
from spotipy.oauth2 import SpotifyClientCredentials
import numpy as np
FEATURE_NAMES = ['acousticness', 'danceability', 'energy', 'instrumentalness',
'liveness', 'loudness', 'speechiness', 'tempo', 'valence']
PLAYLIST_SCOPE = 'playlist-modify-public'
try:
CLIENT_ID = os.environ["CLIENT_ID"]
except:
print("No client ID set.")
try:
CLIENT_SECRET = os.environ["CLIENT_SECRET"]
except:
print("No client secret set.")
try:
REDIRECT_URL = os.environ["REDIRECT_URL"]
except:
print("No redirect url set.")
TRACK_URI_BASE = 'https://open.spotify.com/embed/track/'
def get_client():
"""Generate a fresh Spotify API Client that does not require user authorization.
Returns:
Spotify API Client: API Client to be used for queries not regarding user information.
"""
auth_manager = SpotifyClientCredentials(client_id=CLIENT_ID,client_secret=CLIENT_SECRET)
return spotipy.client.Spotify(auth_manager=auth_manager)
class SpotifyTrack:
""" Object for keeping track of the information provided through the Spotify API on a particular track.
"""
def __init__(self, track_id: str) -> None:
""" Constructor for class.
Args:
track_id (str): ID of the track on the Spotify API.
"""
self.track_id = track_id
client = get_client()
self.raw_track_info = client.track(track_id)
try:
self.track_image = self.raw_track_info["album"]["images"][0]["url"]
except IndexError:
print("No Image could be found for:", self.raw_track_info, "getting a random track.")
self.raw_track_info = client.track(track_id - 1)
self.track_preview_url = self.raw_track_info["preview_url"]
def get_name(self):
return self.raw_track_info["name"]
def get_artist(self):
return self.raw_track_info["artists"][0]["name"]
def get_track_audio_features(self):
client = get_client()
features_dict = client.audio_features(self.track_id)[0]
return np.array([features_dict[feature] for feature in FEATURE_NAMES])
def get_auth_manager() -> spotipy.oauth2.SpotifyOAuth:
""" Generate authentication manager object.
Returns:
spotipy.oauth2.SpotifyOAuth: Spotipy authentication manager.
"""
cache_handler = spotipy.cache_handler.MemoryCacheHandler()
return spotipy.oauth2.SpotifyOAuth(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope=PLAYLIST_SCOPE, redirect_uri=REDIRECT_URL, cache_handler=cache_handler,
show_dialog=True,
open_browser=True)
def search_for_track(track, artist):
"""Search for a track given the name and possible the artist name.
Args:
args (tuple): track name and possible the artist name.
Returns:
_type_: _description_
"""
client = get_client()
if track != "" and artist != "":
search_results = client.search(q = "artist:" + artist + " track:" + track, type = "track", limit=10)
elif track != "":
search_results = client.search(q = "track:" + track, type = "track", limit=10)
elif artist != "":
search_results = client.search(q = "artist:" + artist, type = "track", limit=10)
else:
return {}
return {track_info["name"]+"_"+track_info["artists"][0]["name"]: {"name": track_info["name"],
"artist": track_info["artists"][0]["name"],
"track_id": track_info["id"]} for track_info in search_results["tracks"]["items"]}
def add_tracks_to_playlist(playlist_name:str, population, request: gr.Request) -> bool:
""" Add tracks to a given user's Spotify Library.
Args:
playlist_name (str): Name of the playlist to be created.
auth_url (str): Authorization URL provided by the user.
tracks (List): List of the tracks to be added to the playlist.
Returns:
bool: Flag indicating whether or not the playlist was added to the library succesfully.
"""
if not population.user_key and "referer" in request.request.headers:
auth_manager = get_auth_manager()
code = auth_manager.parse_response_code(request.headers.get("referer"))
token_info = auth_manager.get_access_token(code)
token = token_info['access_token']
population.user_key = token
elif not population.user_key:
return False
user_client = spotipy.Spotify(population.user_key)
username = user_client.current_user()["id"]
try:
playlist_result = user_client.user_playlist_create(username, playlist_name, public=True)
print("playlist created")
except spotipy.exceptions.SpotifyException:
return False
playlist_id = playlist_result["id"]
tracks_to_add = ["spotify:track:" + track.get_track_id() for track in population.playlist_selected_songs]
if tracks_to_add:
user_client.user_playlist_add_tracks(username, playlist_id, tracks_to_add)
return True