Skip to content

PlaylistFilters

When creating playlists, the playlist_builder calls filter_tag_playlists with a configurable list of PlaylistFilter implementations:

Source code in djtools/collection/helpers.py
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
def filter_tag_playlists(
    playlist: Playlist, playlist_filters: List[PlaylistFilter]
) -> None:
    """Applies a list of PlaylistFilter implementations to the playlist.

    If the PlaylistFilter implementations' is_filter_playlist method evaluates
    to True, then the filter_track method is applied to each track in the
    playlist. The playlist's tracks are set to remove the tracks that have been
    filtered out.

    Args:
        playlist: Playlist to potentially have its tracks filtered.
        playlist_filters: A list of PlaylistFilter implementations used to
            filter playlist tracks.
    """
    # This is a folder so filter its playlists.
    if playlist.is_folder():
        for _playlist in playlist:
            filter_tag_playlists(_playlist, playlist_filters)
        return

    # Apply each PlaylistFilter to this playlist.
    for playlist_filter in playlist_filters:
        if not playlist_filter.is_filter_playlist(playlist):
            continue
        playlist.set_tracks(
            tracks={
                track_id: track
                for track_id, track in playlist.get_tracks().items()
                if playlist_filter.filter_track(track)
            },
        )

These PlaylistFilters inject custom behavior into the playlist_builder. In general, this is done by scanning through a playlist structure and looking for a playlist, or playlists, that match some description and then filter for tracks that match another description.

Source code in djtools/collection/playlist_filters.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class PlaylistFilter(ABC):
    "This class defines an interface for filtering tracks from playlists."

    @abstractmethod
    def filter_track(self, track: Track) -> bool:
        """Returns True if this track should remain in the playlist.

        Args:
            track: Track object to apply filter to.

        Returns:
            Whether or not this track should be included in the playlist.
        """

    @abstractmethod
    def is_filter_playlist(self, playlist: Playlist) -> bool:
        """Returns True if this playlist should be filtered.

        Args:
            playlist: Playlist object to potentially filter.

        Returns:
            Whether or not to filter this playlist.
        """

PlaylistFilter subclasses must implement two methods:

  • is_filter_playlist: returns True if a given Playlist should have the filter applied to its tracks
  • filter_track: returns True if a track should remain in the playlist after applying the filter.

Once a PlaylistFilter is implemented, it must be added to the list of supported collection_playlist_filters:

Source code in djtools/collection/config.py
 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
class CollectionConfig(BaseConfigFormatter):
    """Configuration object for the collection package."""

    collection_path: Optional[Path] = None
    collection_playlist_filters: List[PlaylistFilters] = []
    collection_playlists: bool = False
    collection_playlists_remainder: PlaylistRemainder = (
        PlaylistRemainder.FOLDER
    )
    copy_playlists: List[str] = []
    copy_playlists_destination: Optional[Path] = None
    minimum_combiner_playlist_tracks: Optional[PositiveInt] = None
    minimum_tag_playlist_tracks: Optional[PositiveInt] = None
    platform: RegisteredPlatforms = RegisteredPlatforms.REKORDBOX
    shuffle_playlists: List[str] = []
    playlist_config: Optional["PlaylistConfig"] = None

    def __init__(self, *args, **kwargs):
        """Constructor.

        Raises:
            RuntimeError: Using the collection package requires a valid
                collection_path.
            RuntimeError: Failed to render collection_playlist.yaml from
                template.
            RuntimeError: collection_path must be a valid collection path.
            RuntimeError: collection_playlists.yaml must be a valid YAML file.
        """
        super().__init__(*args, **kwargs)

        if any(
            [
                self.collection_playlists,
                self.copy_playlists,
                self.shuffle_playlists,
            ]
        ) and (not self.collection_path or not self.collection_path.exists()):
            raise RuntimeError(
                "Using the collection package requires the config option "
                "collection_path to be a valid collection path"
            )

        if self.collection_playlists:
            config_path = Path(__file__).parent.parent / "configs"
            env = Environment(
                loader=FileSystemLoader(config_path / "playlist_templates")
            )
            playlist_template = None
            playlist_template_name = "collection_playlists.j2"
            playlist_config_path = config_path / "collection_playlists.yaml"

            try:
                playlist_template = env.get_template(playlist_template_name)
            except TemplateNotFound:
                pass

            if playlist_template:
                try:
                    playlist_config = playlist_template.render()
                except Exception as exc:
                    raise RuntimeError(
                        f"Failed to render {playlist_template_name}: {exc}"
                    ) from exc

                if playlist_config_path.exists():
                    logger.warning(
                        f"Both {playlist_template_name} and "
                        f"{playlist_config_path.name} exist. Overwriting "
                        f"{playlist_config_path.name} with the rendered "
                        "template"
                    )

                with open(
                    playlist_config_path, mode="w", encoding="utf-8"
                ) as _file:
                    _file.write(playlist_config)

            if not playlist_config_path.exists():
                raise RuntimeError(
                    "collection_playlists.yaml must exist to use the "
                    "collection_playlists feature"
                )

            try:
                with open(
                    playlist_config_path, mode="r", encoding="utf-8"
                ) as _file:
                    self.playlist_config = PlaylistConfig(
                        **yaml.load(_file, Loader=yaml.FullLoader) or {}
                    )
            except ValidationError as exc:
                raise RuntimeError(
                    "collection_playlists.yaml must be a valid YAML to use "
                    "the collection_playlists feature"
                ) from exc

PlaylistFilter Implementations

The playlist_filters module contains the following set of PlaylistFilter implementations: - HipHopFilter - MinimalDeepTechFilter - TransitionTrackFilter - ComplexTrackFilter

HipHopFilter

  • Checks to see if a playlist named 'Hip Hop' is a child of a playlist named 'Bass'
  • If it is, then tracks in that playlist must have a genre tag besides 'Hip Hop' and 'R&B'
  • If it is not, then tracks in that playlist must have only genre tags 'Hip Hop' and 'R&B'

MinimalDeepTechFilter

  • Checks to see if a playlist named 'Minimal Deep Tech' is a child of a playlist named 'Techno' or 'House'
  • If it's a child of a 'Techno' playlist, then at least one other genre tag must contain the substring 'techno' (case insensitive)
  • If it's a child of a 'House' playlist, then at least one other genre tag must contain the substring 'house'

ComplexTrackFilter

  • Checks to see if the playlist, or a parent playlist, contains the substring 'complex'
  • Filters tracks that contain fewer than a set number of tags (only includes "other" tags, does not include genre tags)
  • When instantiated, ComplexTrackFilter takes optional arguments for the minimum_tags_for_complex_track as well as the list of exclude_tags which may not count towards the total number of tags

TransitionTrackFilter

  • Checks to see if the playlist, or a parent playlist, contains the substring 'transition'
  • Checks to see if the playlist contains one, and only one, of the substrings 'genre' or 'tempo'
  • Filters tracks that contain a special annotation in their comments field
  • The expected annotation must match the following syntax [ token1 / token2] where a token must be strings if it's a 'genre' transition playlist or numbers if it's a 'tempo' transition playlist