PlaylistFilters
When creating playlists, the playlist_builder
calls filter_tag_playlists
with a configurable list of PlaylistFilter
implementations:
Source code in src/djtools/collection/helpers.py
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 | 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 src/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 src/djtools/collection/config.py
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 | class CollectionConfig(BaseConfig):
"""Configuration object for the collection package."""
COLLECTION_PATH: Optional[Path] = None
COLLECTION_PLAYLIST_FILTERS: List[
Literal[
"HipHopFilter",
"MinimalDeepTechFilter",
"ComplexTrackFilter",
"TransitionTrackFilter",
]
] = []
COLLECTION_PLAYLISTS: bool = False
COLLECTION_PLAYLISTS_REMAINDER: Literal["folder", "playlist"] = "folder"
COPY_PLAYLISTS: List[str] = []
COPY_PLAYLISTS_DESTINATION: Optional[Path] = None
PLATFORM: Literal["rekordbox"] = "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'
- 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