{ "cells": [ { "cell_type": "markdown", "source": [ "# Set up Spotify credentials\n", "\n", "Before getting started you need:\n", "\n", "* Spotify API permissions & credentials that could apply for [here](https://developer.spotify.com/). Simply log in, go to your “dashboard” and select “create client id” and follow the instructions. Spotify are not too strict on providing permissions so put anything you like when they ask for commercial application.\n", "\n", "* Python module — spotipy — imported" ], "metadata": { "id": "XnUzjGil6shK" } }, { "cell_type": "code", "source": [ "!pip install gradio" ], "metadata": { "id": "oQ6x5yuCAzUn" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "yCTm2lqN1kuh" }, "outputs": [], "source": [ "!pip install spotipy\n", "import spotipy\n", "#To access authorised Spotify data - https://developer.spotify.com/\n", "from spotipy.oauth2 import SpotifyClientCredentials\n", "!pip install fuzzywuzzy\n", "from fuzzywuzzy import fuzz\n", "import pandas as pd\n", "import seaborn as sns\n", "!pip install gradio\n", "import gradio as gr\n", "#https://gradio.app/docs/#i_slider\n", "import matplotlib.pyplot as plt\n", "import time\n", "import numpy as np" ] }, { "cell_type": "code", "source": [ "#Create Function for identifying your artist\n", "\n", "def choose_artist(name_input, sp):\n", " results = sp.search(name_input)\n", " #result_1 = result['tracks']['items'][0]['artists']\n", " top_matches = []\n", " counter = 0\n", " #for each result item (max 10 I think)\n", " for i in results['tracks']['items']:\n", " #store current item\n", " current_item = results['tracks']['items'][counter]['artists']\n", " counter+=1\n", " #for each item in that search_term\n", " counter2 = 0\n", " for i in current_item:\n", " #append artist name to top_matches\n", " #I will need to append something to identify the correct match, please update once I know\n", " top_matches.append((current_item[counter2]['name'], current_item[counter2]['uri']))\n", " counter2+=1\n", "\n", " #remove duplicates by turning list into a set, then back into a list\n", " top_matches = list(set(top_matches))\n", "\n", " fuzzy_matches = []\n", " #normal list doesn't need len(range)\n", " for i in top_matches:\n", " #put ratio result in variable to avoid errors\n", " ratio = fuzz.ratio(name_input, i[0])\n", " #store as tuple but will need to increase to 3 to include uid\n", " fuzzy_matches.append((i[0], ratio, i[1]))\n", " #sort fuzzy matches by ratio score\n", " fuzzy_matches = sorted(fuzzy_matches, key=lambda tup: tup[1], reverse=True)\n", " #store highest tuple's attributes in chosen variables\n", " chosen = fuzzy_matches[0][0]\n", " chosen_id = fuzzy_matches[0][1]\n", " chosen_uri = fuzzy_matches[0][2]\n", " print(\"The results are based on the artist: \", chosen)\n", " return chosen, chosen_id, chosen_uri" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Hpbj6dLF8LmI", "outputId": "cfc62ba7-1aab-460c-fdee-bac810e0ea52" }, "execution_count": 24, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The results are based on the artist: Unknown T\n" ] } ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "id": "NsjpVGCP1kul" }, "outputs": [], "source": [ "#Function to Pull all of your artist's albums\n", "def find_albums(artist_uri, sp):\n", " sp_albums = sp.artist_albums(artist_uri, album_type='album', limit=50) #There's a 50 album limit\n", " album_names = []\n", " album_uris = []\n", " for i in range(len(sp_albums['items'])):\n", " #Keep names and uris in same order to keep track of duplicate albums\n", " album_names.append(sp_albums['items'][i]['name'])\n", " album_uris.append(sp_albums['items'][i]['uri'])\n", " return album_uris, album_names" ] }, { "cell_type": "code", "source": [ "#Function to store all album details along with their song details\n", "def albumSongs(album, sp, album_count, album_names, spotify_albums):\n", " spotify_albums[album] = {} #Creates dictionary for that specific album\n", " #Create keys-values of empty lists inside nested dictionary for album\n", " spotify_albums[album]['album_name'] = [] #create empty list\n", " spotify_albums[album]['track_number'] = []\n", " spotify_albums[album]['song_id'] = []\n", " spotify_albums[album]['song_name'] = []\n", " spotify_albums[album]['song_uri'] = []\n", "\n", " tracks = sp.album_tracks(album) #pull data on album tracks\n", "\n", " for n in range(len(tracks['items'])): #for each song track\n", " spotify_albums[album]['album_name'].append(album_names[album_count]) #append album name tracked via album_count\n", " spotify_albums[album]['track_number'].append(tracks['items'][n]['track_number'])\n", " spotify_albums[album]['song_id'].append(tracks['items'][n]['id'])\n", " spotify_albums[album]['song_name'].append(tracks['items'][n]['name'])\n", " spotify_albums[album]['song_uri'].append(tracks['items'][n]['uri'])" ], "metadata": { "id": "mgR4WN77iYG0" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "#Add popularity category\n", "def popularity(album, sp, spotify_albums):\n", " #Add new key-values to store audio features\n", " spotify_albums[album]['popularity'] = []\n", " #create a track counter\n", " track_count = 0\n", " for track in spotify_albums[album]['song_uri']:\n", " #pull audio features per track\n", " pop = sp.track(track)\n", " spotify_albums[album]['popularity'].append(pop['popularity'])\n", " track_count+=1" ], "metadata": { "id": "4bgHVdBnpawL" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "def gradio_music_graph(client_id, client_secret, artist_name): #total_albums\n", " #Insert your credentials\n", " client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)\n", " sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) #spotify object to access API\n", " #Choose your artist via input\n", " chosen_artist, ratio_score, artist_uri = choose_artist(artist_name, sp=sp)\n", " #Retrieve their album details\n", " album_uris, album_names = find_albums(artist_uri, sp=sp)\n", " #Create dictionary to store all the albums\n", " spotify_albums = {}\n", " #Album count tracker\n", " album_count = 0\n", " for i in album_uris: #for each album\n", " albumSongs(i, sp=sp, album_count=album_count, album_names=album_names, spotify_albums=spotify_albums)\n", " print(\"Songs from \" + str(album_names[album_count]) + \" have been added to spotify_albums dictionary\")\n", " album_count+=1 #Updates album count once all tracks have been added\n", " \n", " #To avoid it timing out\n", " sleep_min = 2\n", " sleep_max = 5\n", " start_time = time.time()\n", " request_count = 0\n", " #Update albums with popularity scores\n", " for album in spotify_albums:\n", " popularity(album, sp=sp, spotify_albums=spotify_albums)\n", " request_count+=1\n", " if request_count % 5 == 0:\n", " # print(str(request_count) + \" playlists completed\")\n", " time.sleep(np.random.uniform(sleep_min, sleep_max))\n", " # print('Loop #: {}'.format(request_count))\n", " # print('Elapsed Time: {} seconds'.format(time.time() - start_time))\n", "\n", " #Create song dictonary to convert into Dataframe \n", " dic_df = {} \n", "\n", " dic_df['album_name'] = []\n", " dic_df['track_number'] = []\n", " dic_df['song_id'] = []\n", " dic_df['song_name'] = []\n", " dic_df['song_uri'] = []\n", " dic_df['popularity'] = []\n", "\n", " for album in spotify_albums: \n", " for feature in spotify_albums[album]:\n", " dic_df[feature].extend(spotify_albums[album][feature])\n", " #Convert into dataframe\n", "\n", " df = pd.DataFrame.from_dict(dic_df)\n", " df = df.sort_values(by='popularity')\n", " df = df.drop_duplicates(subset=['song_id'], keep=False)\n", "\n", " sns.set_style('ticks')\n", "\n", " fig, ax = plt.subplots()\n", " fig.set_size_inches(11, 8)\n", " ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha=\"right\")\n", " plt.tight_layout()\n", "\n", " sns.boxplot(x=df[\"album_name\"], y=df[\"popularity\"], ax=ax)\n", " fig.savefig('artist_popular_albums.png')\n", " plt.show()\n", " # plt.plot(projected_values.T)\n", " # plt.legend(employee_data[\"Name\"])\n", " # return employee_data, plt.gcf(), regression_values\n", " return df\n", "#Interface will include these buttons based on parameters in the function with a dataframe output\n", "music_plots = gr.Interface(gradio_music_graph, [\"text\", \"text\", \"text\"], \n", " [\"dataframe\", \"plot\"], title=\"Popular Songs By Album Box Plot Distribution on Spotify\", description=\"Using your Spotify API Access from https://developer.spotify.com/ you can see your favourite artist's most popular albums on Spotify\")\n", "\n", "music_plots.launch(debug=True)" ], "metadata": { "id": "bUr9kLB-7CBj" }, "execution_count": null, "outputs": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.4" }, "colab": { "name": "Most Popular Albums Per Artist With Gradio.ipynb", "provenance": [], "collapsed_sections": [] } }, "nbformat": 4, "nbformat_minor": 0 }