44 lines
1.1 KiB
Python
44 lines
1.1 KiB
Python
"""
|
|
Selectors for working with individual tracks
|
|
"""
|
|
from typing import Iterable, Union
|
|
|
|
from spotify_model import SimplifiedTrack, Track
|
|
from spotipy import Spotify
|
|
|
|
from .util import chunk
|
|
|
|
|
|
def track_from_ids(
|
|
client: Spotify, tracks: Union[Iterable[str], Iterable[SimplifiedTrack]], chunk_size: int = 50
|
|
) -> Iterable[Track]:
|
|
"""
|
|
Given a stream of track IDs (or simplified tracks), retrieve the full track objects
|
|
"""
|
|
|
|
def _to_id() -> Iterable[Track]:
|
|
for track in tracks:
|
|
yield track if isinstance(track, str) else track.spotify_id
|
|
|
|
for track_id_chunk in chunk(_to_id(), chunk_size):
|
|
track_chunk = client.tracks(track_id_chunk)
|
|
|
|
for track in track_chunk:
|
|
yield Track(**track)
|
|
|
|
|
|
def track_unique_albums(tracks: Iterable[Track]) -> Iterable[str]:
|
|
"""
|
|
Given a stream of tracks, yield all unique album IDs
|
|
"""
|
|
|
|
album_ids = set()
|
|
|
|
for track in tracks:
|
|
album_id = track.album.spotify_id
|
|
if album_id in album_ids:
|
|
continue
|
|
|
|
album_ids.add(album_id)
|
|
yield album_id
|