File size: 11,898 Bytes
9dd7d9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/Bryan-Az/Neurobytes/blob/main/notebooks/test_spotify_api.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "zQVPVULlQjLy",
        "outputId": "d949a567-1ee8-4b51-e544-5e6c1888f4e8"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Requirement already satisfied: python-dotenv in /usr/local/lib/python3.10/dist-packages (1.0.1)\n"
          ]
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "True"
            ]
          },
          "metadata": {},
          "execution_count": 9
        }
      ],
      "source": [
        "import requests\n",
        "# access colab secrets .env\n",
        "!pip install python-dotenv\n",
        "from dotenv import load_dotenv\n",
        "load_dotenv()"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Data Related to the Spotify API"
      ],
      "metadata": {
        "id": "rx--dKrrWFAX"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "Main Discovery Objective:\n",
        "To identify data that can provide Song-to-Song similarity information based on musicality.\n",
        "\n",
        "\n",
        "---\n",
        "\n",
        "The spotify API is able to retrieve data for select artists, albums and shows and other collections within Spotify's content like podcasts or playlists that may help us build alternative sets of information outside of the API from where we can begin."
      ],
      "metadata": {
        "id": "0fZ70UJFWtQr"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "SPOTIFY_CLIENT_ID = os.getenv('client_id')\n",
        "SPOTIFY_CLIENT_SECRET = os.getenv('client_secret')"
      ],
      "metadata": {
        "id": "rj6PkYhtRbex"
      },
      "execution_count": 10,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": 88,
      "metadata": {
        "id": "n8zRio2XQjLz"
      },
      "outputs": [],
      "source": [
        "def get_access_token(client_id, client_secret):\n",
        "    url = 'https://accounts.spotify.com/api/token'\n",
        "    headers = {\n",
        "        'Content-Type': 'application/x-www-form-urlencoded'\n",
        "    }\n",
        "    payload = {\n",
        "        'grant_type': 'client_credentials'\n",
        "    }\n",
        "    response = requests.post(url, headers=headers, data=payload, auth=(client_id, client_secret))\n",
        "    if response.status_code == 200:\n",
        "        return response.json()['access_token']\n",
        "    else:\n",
        "        raise Exception(\"Failed to retrieve access token\")\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 89,
      "metadata": {
        "id": "LGblk66xQjL0"
      },
      "outputs": [],
      "source": [
        "access_token = get_access_token(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET)"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Artist-Specific Data"
      ],
      "metadata": {
        "id": "20wfCc7pV-Tk"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 95,
      "metadata": {
        "id": "KU5bUwqjQjL1"
      },
      "outputs": [],
      "source": [
        "def get_artist_data(access_token, artist_id):\n",
        "    '''\n",
        "    This function retrieves artist data from the Spotify API using the provided access token and artist ID.\n",
        "    '''\n",
        "    url = f'https://api.spotify.com/v1/artists/{artist_id}'\n",
        "    headers = {\n",
        "        'Authorization': f'Bearer {access_token}'\n",
        "    }\n",
        "    response = requests.get(url, headers=headers)\n",
        "    if response.status_code == 200:\n",
        "        return response.json()\n",
        "    else:\n",
        "        if response.status_code == 404:\n",
        "            raise Exception(\"Artist not found\")\n",
        "        elif response.status_code == 401:\n",
        "            get_access_token(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET)\n",
        "            return get_artist_data(access_token, artist_id)\n",
        "        else:\n",
        "          raise Exception(\"Failed to retrieve artist data\")\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 91,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "DP3CBI7EQjL2",
        "outputId": "ad4edf96-d819-4bd3-e6e4-09e65895c753"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{'external_urls': {'spotify': 'https://open.spotify.com/artist/1vCWHaC5f2uS3yhpwWbIA6'}, 'followers': {'href': None, 'total': 22658238}, 'genres': ['dance pop', 'edm', 'pop', 'pop dance'], 'href': 'https://api.spotify.com/v1/artists/1vCWHaC5f2uS3yhpwWbIA6', 'id': '1vCWHaC5f2uS3yhpwWbIA6', 'images': [{'height': 640, 'url': 'https://i.scdn.co/image/ab6761610000e5ebae07171f989fb39736674113', 'width': 640}, {'height': 320, 'url': 'https://i.scdn.co/image/ab67616100005174ae07171f989fb39736674113', 'width': 320}, {'height': 160, 'url': 'https://i.scdn.co/image/ab6761610000f178ae07171f989fb39736674113', 'width': 160}], 'name': 'Avicii', 'popularity': 78, 'type': 'artist', 'uri': 'spotify:artist:1vCWHaC5f2uS3yhpwWbIA6'}\n"
          ]
        }
      ],
      "source": [
        "artist_id = '1vCWHaC5f2uS3yhpwWbIA6'  # This is the artist ID for Avicii\n",
        "artist_data = get_artist_data(access_token, artist_id)\n",
        "print(artist_data)"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "artist_data.keys()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "lM4V2WtzYrx_",
        "outputId": "818de95e-ee31-48a0-cbbb-5951f84df08b"
      },
      "execution_count": 96,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "dict_keys(['external_urls', 'followers', 'genres', 'href', 'id', 'images', 'name', 'popularity', 'type', 'uri'])"
            ]
          },
          "metadata": {},
          "execution_count": 96
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "artist_data['genres']"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ZoG-4QUemGg3",
        "outputId": "bac86f37-b181-4867-9e02-83d8258aed08"
      },
      "execution_count": 127,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['dance pop', 'edm', 'pop', 'pop dance']"
            ]
          },
          "metadata": {},
          "execution_count": 127
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "def get_artist_albums(access_token, artist_id):\n",
        "  '''\n",
        "  This function retrieves a list of albums for a given artist using the Spotify API.\n",
        "  returns: list of albums for the artist\n",
        "  '''\n",
        "  # part 1 extracts the album information without the tracks\n",
        "  include_groups = 'album'\n",
        "  url = f'https://api.spotify.com/v1/artists/{artist_id}/albums/?include_groups={include_groups}'\n",
        "  headers = {\n",
        "      'Authorization': f'Bearer {access_token}'\n",
        "  }\n",
        "  response = requests.get(url, headers=headers)\n",
        "  if response.status_code == 200:\n",
        "        return response.json()\n",
        "  else:\n",
        "      if response.status_code == 404:\n",
        "          raise Exception(\"Artist not found\")\n",
        "      elif response.status_code == 401:\n",
        "          get_access_token(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET)\n",
        "          return 'Try again, new token generated'\n",
        "      else:\n",
        "        raise Exception(\"Failed to retrieve artist data\")"
      ],
      "metadata": {
        "id": "lRMDVG0CY_xr"
      },
      "execution_count": 122,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# setting include_group to album only to return only this artists own albums\n",
        "artist_albums = get_artist_albums(access_token, artist_id)"
      ],
      "metadata": {
        "id": "IXZFbWG-ZGvN"
      },
      "execution_count": 123,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "The available metadata available for the artist album's returned."
      ],
      "metadata": {
        "id": "KzKBzVnBa2Gc"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# might be redundant information if the include_group is set\n",
        "for i in artist_albums:\n",
        "  print(i['name'] + ' ' + i['album_group'] + ' '+ i['album_type'])"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "lfEf-p2ybHWW",
        "outputId": "fe39c159-cefa-4633-83a6-798e0ce1a651"
      },
      "execution_count": 78,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "TIM album album\n",
            "Stories album album\n",
            "True: Avicii By Avicii album album\n",
            "The Days / Nights album album\n",
            "True (Bonus Edition) album album\n",
            "True album album\n",
            "Malo (The Cube Guys Remix) single single\n",
            "Street Dancer (Sgt Slick's Discotizer 2022 Remix) single single\n",
            "My Feelings For You (Mark Knight Remix) single single\n",
            "My Feelings For You (Don Diablo Remix) single single\n",
            "Forever Yours (Avicii Tribute) single single\n",
            "Fades Away (feat. MishCatt) [Tribute Concert Version] single single\n",
            "Heaven (David Guetta & MORTEN Remix) single single\n",
            "Tough Love (Tiësto Remix) single single\n",
            "SOS (Laidback Luke Tribute Remix) single single\n",
            "Tough Love (feat. Vargas & Lagola) single single\n",
            "SOS (feat. Aloe Blacc) single single\n",
            "Lonely Together (Remixes) single single\n",
            "Lonely Together (Acoustic) single single\n",
            "Without You (Remixes) single single\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "G4IPmxegYmHN"
      },
      "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.8.19"
    },
    "colab": {
      "provenance": [],
      "include_colab_link": true
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}