Skip to content

Managers

Operations on spotify playlists.

create(name, description='Randomly Generated Mix', overwrite=True)

Create a new, empty, playlist.

Warning

If the name of the playlist is an existing playlist, and overwrite is True, the said playlist will be emptied.

Parameters:

Name Type Description Default
name str

name of your playlist.

required
description str

description of your playlist

'Randomly Generated Mix'
overwrite bool

Overwrite the existing playlist if the name is already used.

True

Returns:

Type Description
PlaylistData

Created playlist

Source code in chopin/managers/playlist.py
def create(name: str, description: str = "Randomly Generated Mix", overwrite: bool = True) -> PlaylistData:
    """Create a new, empty, playlist.

    !!! warning
        If the `name` of the playlist is an existing playlist, and overwrite is `True`, the said playlist will
        be emptied.

    Args:
        name: name of your playlist.
        description: description of your playlist
        overwrite: Overwrite the existing playlist if the `name` is already used.

    Returns:
        Created playlist
    """
    user_playlists = get_user_playlists()
    target_playlist = [playlist for playlist in user_playlists if playlist.name == simplify_string(name)]
    if target_playlist:
        if overwrite:
            replace_tracks_in_playlist(target_playlist[0].id, [])
            return target_playlist[0]
        else:
            raise ValueError(
                f"Trying to create a playlist {name} but there is already such a playlist."
                "Use `overwrite=True` if you want to erase the playlist."
            )
    return create_playlist(name=name, description=description)

create_playlist(name, description='Playlist created with Chopin')

Create a playlist in the user library.

Parameters:

Name Type Description Default
name str

Name for the playlist

required
description str

Optional description for the playlist

'Playlist created with Chopin'

Returns:

Type Description
PlaylistData

Created playlist data.

Source code in chopin/managers/playlist.py
def create_playlist(name: str, description: str = "Playlist created with Chopin") -> PlaylistData:
    """Create a playlist in the user library.

    Args:
        name: Name for the playlist
        description: Optional description for the playlist

    Returns:
        Created playlist data.
    """
    user = get_current_user()
    return create_user_playlist(user_id=user.id, name=name, description=description)

create_playlist_from_queue(name, description='Mix generated from queue')

Create a playlist from the user's queue.

Parameters:

Name Type Description Default
name str

The name of the playlist

required
description str

An optional description

'Mix generated from queue'

Returns:

Type Description
PlaylistData

The created playlist

Notes

Due to Spotify limitations, only 20 songs from the queue can be fetched and added to the playlist.

Source code in chopin/managers/playlist.py
def create_playlist_from_queue(name: str, description: str = "Mix generated from queue") -> PlaylistData:
    """Create a playlist from the user's queue.

    Args:
        name: The name of the playlist
        description: An optional description

    Returns:
        The created playlist

    Notes:
        Due to Spotify limitations, only 20 songs from the queue can be fetched and added to the playlist.
    """
    playlist = create(name, description, overwrite=True)
    tracks = get_queue()
    fill(uri=playlist.uri, tracks=tracks)
    return playlist

doppelganger_playlist(source_playlist, new_playlist)

Create a "doppelganger", a similar playlist from an existing one.

Parameters:

Name Type Description Default
source_playlist str

The name of the playlist to copy.

required
new_playlist str

The name of the new playlist.

required

Returns:

Type Description
PlaylistData

The created playlist.

Source code in chopin/managers/playlist.py
def doppelganger_playlist(source_playlist: str, new_playlist: str) -> PlaylistData:
    """Create a "doppelganger", a similar playlist from an existing one.

    Args:
        source_playlist: The name of the playlist to copy.
        new_playlist: The name of the new playlist.

    Returns:
        The created playlist.
    """
    playlist = get_named_playlist(source_playlist)
    tracks = get_playlist_tracks(playlist.id)

    albums_tracks: dict[str, list[TrackData]] = {}
    new_tracks: list[TrackData] = []
    for track in tracks:
        album_id = track.album.id
        if album_id not in albums_tracks:
            albums_tracks[album_id] = get_album_tracks(album_id)
        new_tracks.append(random.choice(albums_tracks[album_id]))

    if new_tracks:
        doppelganger_playlist = create(new_playlist, overwrite=True)
        fill(doppelganger_playlist.id, tracks=new_tracks)
        return doppelganger_playlist
    logger.info(f"No tracks could be generated from playlist {source_playlist}. The {new_playlist} was not created.")

dump(playlist, filepath)

Dump a playlist in a JSON format.

Parameters:

Name Type Description Default
playlist PlaylistSummary

The playlist to write

required
filepath Path

Target file to receive the dump

required
Source code in chopin/managers/playlist.py
def dump(playlist: PlaylistSummary, filepath: Path):
    """Dump a playlist in a JSON format.

    Args:
        playlist: The playlist to write
        filepath: Target file to receive the dump
    """
    json_str = playlist.model_dump_json()
    with open(filepath, "w") as f:
        f.write(json_str)

fill(uri, tracks)

Fill a playlist with tracks.

Note

Duplicate tracks will be removed.

Parameters:

Name Type Description Default
uri str

uri of the playlist to fill

required
tracks list[TrackData]

List of track uuids to add to the playlist

required
Source code in chopin/managers/playlist.py
def fill(uri: str, tracks: list[TrackData]):
    """Fill a playlist with tracks.

    !!! note
        Duplicate tracks will be removed.

    Args:
        uri: uri of the playlist to fill
        tracks: List of track uuids to add to the playlist
    """
    track_ids = list(set([track.id for track in tracks]))
    add_tracks_to_playlist(uri, track_ids)

shuffle_playlist(name)

Fetch a playlist from its name and shuffle_playlist it.

Parameters:

Name Type Description Default
name str

playlist name.

required

Returns:

Type Description
PlaylistData

Shuffled playlist data.

Raises:

Type Description
ValueError

If the playlist name was not found.

Source code in chopin/managers/playlist.py
def shuffle_playlist(name: str) -> PlaylistData:
    """Fetch a playlist from its name and shuffle_playlist it.

    Args:
        name: playlist name.

    Returns:
        Shuffled playlist data.

    Raises:
        ValueError: If the playlist name was not found.
    """
    playlist = get_named_playlist(name)
    if not playlist:
        raise ValueError(f"Playlist {name} not found.")

    tracks = get_playlist_tracks(playlist.id)
    tracks = shuffle_tracks(tracks)
    replace_tracks_in_playlist(playlist.id, track_ids=[track.id for track in tracks])
    return playlist

summarize_playlist(playlist)

From a given playlist, create its summary.

Summaries are useful to describe and backup playlists. They contain extensive information about tracks, features, and can be serialized.

Parameters:

Name Type Description Default
playlist PlaylistData

The playlist to summarize.

required

Returns:

Type Description
PlaylistSummary

A playlist summary, with extended informations about tracks and statistics.

Source code in chopin/managers/playlist.py
def summarize_playlist(playlist: PlaylistData) -> PlaylistSummary:
    """From a given playlist, create its summary.

    Summaries are useful to describe and backup playlists. They contain extensive information about tracks,
    features, and can be serialized.

    Args:
        playlist: The playlist to summarize.

    Returns:
        A playlist summary, with extended informations about tracks and statistics.
    """
    tracks = get_playlist_tracks(playlist.id)
    return PlaylistSummary(playlist=playlist, tracks=tracks)

tracks_from_playlist_name(playlist_name, nb_tracks, user_playlists, release_range=None, selection_method=None)

Get a number of tracks from a playlist.

Parameters:

Name Type Description Default
playlist_name str

The name of your playlist

required
nb_tracks int

Number of tracks to retrieve

required
user_playlists list[PlaylistData]

List of existing user playlists. Used to map the name with the URI.

required
release_range ReleaseRange | None

An optional datetime range for the release date of the tracks.

None
selection_method SelectionMethod | None

How tracks are chosen from the retrieved tracks. See SelectionMethod for available methods. If no method is given, the choice will be random.

None

Returns:

Type Description
list[TrackData]

A list of track data from the playlists

Source code in chopin/managers/playlist.py
def tracks_from_playlist_name(
    playlist_name: str,
    nb_tracks: int,
    user_playlists: list[PlaylistData],
    release_range: ReleaseRange | None = None,
    selection_method: SelectionMethod | None = None,
) -> list[TrackData]:
    """Get a number of tracks from a playlist.

    Args:
        playlist_name: The name of your playlist
        nb_tracks: Number of tracks to retrieve
        user_playlists: List of existing user playlists. Used to map the name with the URI.
        release_range: An optional datetime range for the release date of the tracks.
        selection_method: How tracks are chosen from the retrieved tracks.
            See `SelectionMethod` for available methods. If no method is given, the choice will be random.

    Returns:
        A list of track data from the playlists
    """
    playlist = [
        playlist for playlist in user_playlists if simplify_string(playlist_name) == simplify_string(playlist.name)
    ]
    if not playlist:
        logger.warning(f"Couldn't retrieve tracks for playlist {playlist_name}")
        return []
    tracks = get_playlist_tracks(playlist_id=playlist[0].id, release_date_range=release_range)
    return select_tracks(tracks, nb_tracks, selection_method)

tracks_from_playlist_uri(playlist_uri, nb_tracks, release_range=None, selection_method=None)

Get tracks from a playlist URI.

Spotify API depreciation

It must be a public playlist, and the playlist must not be owned by Spotify.

Parameters:

Name Type Description Default
playlist_uri str

Name of the artist or band to fetch related tracks from

required
nb_tracks int

Number of tracks to retrieve.

required
release_range ReleaseRange | None

An optional datetime range for the release date of the tracks.

None
selection_method SelectionMethod | None

How tracks are chosen from the retrieved tracks. See SelectionMethod for available methods. If no method is given, the choice will be random.

None

Returns:

Type Description
list[TrackData]

A list of track data from the artist radio.

Source code in chopin/managers/playlist.py
def tracks_from_playlist_uri(
    playlist_uri: str,
    nb_tracks: int,
    release_range: ReleaseRange | None = None,
    selection_method: SelectionMethod | None = None,
) -> list[TrackData]:
    """Get tracks from a playlist URI.

    !!! warning "Spotify API depreciation"
        It must be a _public_ playlist, and the playlist _must not be owned_ by Spotify.

    Args:
        playlist_uri: Name of the artist or band to fetch related tracks from
        nb_tracks: Number of tracks to retrieve.
        release_range: An optional datetime range for the release date of the tracks.
        selection_method: How tracks are chosen from the retrieved tracks.
            See `SelectionMethod` for available methods. If no method is given, the choice will be random.

    Returns:
        A list of track data from the artist radio.
    """
    try:
        tracks = get_playlist_tracks(playlist_id=playlist_uri, release_date_range=release_range)
    except Exception:
        logger.warning(f"Couldn't retrieve playlist URI {playlist_uri}")
        return []
    return select_tracks(tracks, nb_tracks, selection_method)

Operations on spotify tracks.

save_tracks(tracks)

Add tracks to the current user liked songs.

Parameters:

Name Type Description Default
tracks list[TrackData]

Tracks to add

required
Source code in chopin/managers/track.py
def save_tracks(tracks: list[TrackData]):
    """Add tracks to the current user liked songs.

    Args:
        tracks: Tracks to add
    """
    track_uris = [track.uri for track in tracks]
    like_tracks(track_uris)

shuffle_tracks(tracks)

Shuffle a list of tracks.

Parameters:

Name Type Description Default
tracks list[TrackData]

Tracks to shuffle_playlist

required

Returns:

Type Description
list[TrackData]

Updated list of tracks

Source code in chopin/managers/track.py
def shuffle_tracks(tracks: list[TrackData]) -> list[TrackData]:
    """Shuffle a list of tracks.

    Args:
        tracks: Tracks to shuffle_playlist

    Returns:
        Updated list of tracks
    """
    return random.sample(tracks, len(tracks))