{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import spotipy\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import requests\n",
    "from spotipy import oauth2\n",
    "\n",
    "SPOTIPY_CLIENT_ID = '7094b9a237704754bcf84abad7f4fd07'\n",
    "SPOTIPY_CLIENT_SECRET = '4f88772687154fcbb263aa909ca39a90'\n",
    "SCOPE = ('user-read-recently-played,user-library-read,user-read-currently-playing,playlist-read-private,playlist-modify-private,playlist-modify-public,user-read-email,user-modify-playback-state,streaming,app-remote-control,user-read-private,user-read-playback-state')\n",
    "SPOTIPY_REDIRECT_URI = 'https://daftjoe.github.io/'\n",
    "sp_oauth = oauth2.SpotifyOAuth( SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET,SPOTIPY_REDIRECT_URI,scope=SCOPE )\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Enter the URL you were redirected to: https://daftjoe.github.io/?code=AQA1R5aEDV5u1xWObhqZA4CGJNSUwKH9nMiHcStCVdxJhBsFcqxCU5BkFcxT1jMO5MuSq5lnpRX_NvsjUWWibPbOWHKK5G-7-ndccfiVtFeGP11yZhuZGo3Bj-nIel0RYCoxU9vPKY4BiL861RduMWAJlUPBACXIAwgTQVVYIbCWOeJnElOFaR7eQZ4yytxT4cZouSvBBP1aP1asNYPj1veGAoq-ON-O1Uv64IXeB0DgGEHcHNKjoDCUWrewkMvTXsk4NiM5O77wo86xPAmLq-Gf77WTpLl1CuZ5H81ow8DDZCnchU4-84KNUWRVsNDbwgPhxJVwGSNLQoyuMznoDbj_hK_90RBcGGNUfnYzdZMUotES-adkEFT2-y39I_gSXqkPBm7xMCZGsRGuoNEHudY6HkVuGsj4pwTmZ7WzeyKNgcO61I2KcImQ_IZBrBD4VoZV2QBGuY8EdTxuZNCtunTiG8KQLGFj2HJdtazYpBuQEv4XL3EPBZzVjOflzPnhxCYODVC5SnEpiw\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "<ipython-input-2-c8c6144fe33e>:3: DeprecationWarning: You're using 'as_dict = True'.get_access_token will return the token string directly in future versions. Please adjust your code accordingly, or use get_cached_token instead.\n",
      "  get_cached_token = sp_oauth.get_access_token(code)\n"
     ]
    }
   ],
   "source": [
    "#browser will open and you have to copy and paste the url after clicking \"Accept\"\n",
    "code = sp_oauth.get_auth_response(open_browser=True)\n",
    "token = sp_oauth.get_access_token(code)\n",
    "refresh_token = token['refresh_token']\n",
    "sp = spotipy.Spotify(token['access_token'])\n",
    "username = sp.current_user()['id']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#create playlist and save playlist id\n",
    "pl_name = 'myEndlessPlaylist1'\n",
    "result = sp.user_playlist_create(username, name=pl_name)\n",
    "pl_id = result['id']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "#ID for the public spotify playlist we're getting all the albums from \n",
    "top_album_pl = '70n5zfYco8wG777Ua2LlNv'\n",
    "\n",
    "#top_albums is list we'll use to make the top albums playlist\n",
    "top_albums = []\n",
    "offset = 0\n",
    "while True:\n",
    "    response = sp.playlist_items(top_album_pl,\n",
    "                                 offset=offset)\n",
    "    \n",
    "    if len(response['items']) == 0:\n",
    "        break\n",
    "    top_albums +=response['items']\n",
    "    offset = offset + len(response['items'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Here we make a DataFrame of all the top albums by looping through that list of response of dictionaries\n",
    "album_df = []\n",
    "for album in top_albums:\n",
    "    \n",
    "    track = album['track']['name']\n",
    "    artist = album['track']['artists'][0]['name']\n",
    "    album_name = album['track']['album']['name']\n",
    "    track_id = album['track']['id']\n",
    "    album_id = album['track']['album']['id']\n",
    "    album_df.append([track,artist,album_name, track_id,album_id])\n",
    "album_df = pd.DataFrame(album_df, columns =['track','artist','album','track_id','album_id'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "<ipython-input-6-8cde892d9b8b>:28: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will *not* be treated as literal strings when regex=True.\n",
      "  album_df.loc[(album_df['track'].str.contains(r\"\\\\\")),'track'] = album_df.track.str.replace('\\\\','')\n"
     ]
    }
   ],
   "source": [
    "\n",
    "#random seed so others can get the same album order as me\n",
    "np.random.seed(10)\n",
    "\n",
    "#make a DataFrame of all albums and add a random number between 0-1 \"rand_key\" for each album\n",
    "all_albums = album_df.drop_duplicates('album_id').album_id\n",
    "all_albums = pd.DataFrame(all_albums).reset_index(drop=True)\n",
    "all_albums['rand_key'] = np.random.rand(len(all_albums))\n",
    "\n",
    "#merge the albums DataFrame back with the full top albums DataFrame\n",
    "album_df = pd.merge(album_df, all_albums, how='inner', on='album_id')\n",
    "\n",
    "#sort by the rand_key (and by index so the songs within albums stay in order)\n",
    "album_df['idx'] = album_df.index\n",
    "album_df = album_df.sort_values(['rand_key','idx']).reset_index(drop=True)\n",
    "\n",
    "#run the code below to exclude one-track albums\n",
    "album_df_piv = pd.pivot_table(album_df, index='album_id',values='track_id',aggfunc='count')\n",
    "album_df_piv.columns = ['num_tracks']\n",
    "album_df = pd.merge(album_df, album_df_piv, how='left',left_on='album_id',right_index=True)\n",
    "album_df = album_df[album_df.num_tracks>1].reset_index(drop=True)\n",
    "\n",
    "album_df['idx'] = album_df.index\n",
    "\n",
    "#do some data cleaning (getting rid of quotes, backslashes) so it will play nice \n",
    "album_df.loc[(album_df['track'].str.contains('\"')),'track'] = album_df.track.str.replace('\"','')\n",
    "album_df.loc[(album_df['artist'].str.contains('\"')),'artist'] = album_df.artist.str.replace('\"','')\n",
    "album_df.loc[(album_df['album'].str.contains('\"')),'album'] = album_df.album.str.replace('\"','')\n",
    "album_df.loc[(album_df['track'].str.contains(r\"\\\\\")),'track'] = album_df.track.str.replace('\\\\','')\n",
    "\n",
    "#copy this album df to your clipboard to paste into google sheets or elsewhere.\n",
    "album_df.to_clipboard(index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'snapshot_id': 'MixhZWY0ODdjMjExNDg5ZWUzMDc3ZDgxYWU3YWIzMzVjZjA4NDAwZDU3'}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#initialize playlist of length 30\n",
    "pl_length = 30\n",
    "last_tracks_added = album_df.loc[0:pl_length-1]\n",
    "tracks_to_add = last_tracks_added.track_id.tolist()\n",
    "sp.playlist_add_items(pl_id,tracks_to_add )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.9.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
