68 lines
2.2 KiB
Python
Raw Normal View History

"""Spotify reader."""
2023-02-24 23:39:32 -08:00
from typing import List, Optional
from llama_index.readers.base import BaseReader
from llama_index.readers.schema.base import Document
2023-02-24 23:39:32 -08:00
class SpotifyReader(BaseReader):
"""Spotify Reader.
2023-02-24 23:39:32 -08:00
Read a user's saved albums, tracks, or playlists from Spotify.
"""
def load_data(self, collection: Optional[str] = "albums") -> List[Document]:
"""Load data from a user's Spotify account.
2023-02-24 23:39:32 -08:00
Args:
collections (Optional[str]): "albums", "tracks", or "playlists"
"""
2023-02-24 23:39:32 -08:00
import spotipy
from spotipy.oauth2 import SpotifyOAuth
2023-02-24 23:39:32 -08:00
scope = "user-library-read"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
results = []
2023-02-24 23:39:32 -08:00
if collection == "albums":
response = sp.current_user_saved_albums()
2023-02-24 23:39:32 -08:00
items = response["items"]
for item in items:
2023-02-24 23:39:32 -08:00
album = item["album"]
album_name = album["name"]
artist_name = album["artists"][0]["name"]
album_string = f"Album {album_name} by Artist {artist_name}\n"
results.append(Document(album_string))
elif collection == "tracks":
response = sp.current_user_saved_tracks()
2023-02-24 23:39:32 -08:00
items = response["items"]
for item in items:
2023-02-24 23:39:32 -08:00
track = item["track"]
track_name = track["name"]
artist_name = track["artists"][0]["name"]
artist_string = f"Track {track_name} by Artist {artist_name}\n"
results.append(Document(artist_string))
elif collection == "playlists":
response = sp.current_user_playlists()
2023-02-24 23:39:32 -08:00
items = response["items"]
for item in items:
2023-02-24 23:39:32 -08:00
playlist_name = item["name"]
owner_name = item["owner"]["display_name"]
playlist_string = f"Playlist {playlist_name} created by {owner_name}\n"
results.append(Document(playlist_string))
else:
2023-02-24 23:39:32 -08:00
raise ValueError(
"Invalid collection parameter value. Allowed values are 'albums', 'tracks', or 'playlists'."
)
return results
2023-02-24 23:39:32 -08:00
if __name__ == "__main__":
reader = SpotifyReader()
2023-02-24 23:39:32 -08:00
print(reader.load_data())