-
Notifications
You must be signed in to change notification settings - Fork 4
/
track.py
502 lines (408 loc) · 16.6 KB
/
track.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
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
302
303
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
"""A Track in the database and any related logic."""
import logging
from pathlib import Path
from typing import Any, Optional
import mediafile
import pluggy
from sqlalchemy import JSON, Integer
from sqlalchemy.ext.mutable import MutableDict, MutableSet
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.schema import ForeignKey, UniqueConstraint
import moe
from moe import config
from moe.library.album import Album, MetaAlbum
from moe.library.lib_item import LibItem, LibraryError, MetaLibItem, SABase, SetType
__all__ = ["MetaTrack", "Track", "TrackError"]
log = logging.getLogger("moe.track")
class Hooks:
"""Track hook specifications."""
@staticmethod
@moe.hookspec
def is_unique_track(track: "Track", other: "Track") -> bool: # type: ignore
"""Add new conditions to determine whether two tracks are unique.
"Uniqueness" is meant in terms of whether the two tracks should be considered
duplicates in the library. These additional conditions will be applied inside a
track's :meth:`is_unique` method.
"""
@staticmethod
@moe.hookspec
def read_custom_tags(
track_path: Path, album_fields: dict[str, Any], track_fields: dict[str, Any]
) -> None:
"""Read and set any fields from a track_path.
How you read the file and assign tags is up to each individual plugin.
Internally, Moe uses the `mediafile <https://github.com/beetbox/mediafile>`_
library to read tags.
Args:
track_path: Path of the track file to read.
album_fields: Dictionary of album fields to read from the given track file's
tags. The dictionary may contain existing fields and values, and you
can choose to either override the existing fields, or to provide new
fields.
track_fields: Dictionary of track fields to read from the given track file's
tags. The dictionary may contain existing fields and values, and you
can choose to either override the existing fields, or to provide new
fields.
Example:
.. code:: python
audio_file = mediafile.MediaFile(track_path)
album_fields["title"] = audio_file.album
track_fields["title"] = audio_file.title
See Also:
* :ref:`Album and track fields <fields:Fields>`
* `Mediafile docs <https://mediafile.readthedocs.io/en/latest/>`_
* The :meth:`~moe.write.Hooks.write_custom_tags` hook for writing
tags.
"""
@moe.hookimpl
def add_hooks(pm: pluggy._manager.PluginManager):
"""Registers `track` hookspecs to Moe."""
from moe.library.track import Hooks
pm.add_hookspecs(Hooks)
@moe.hookimpl(tryfirst=True)
def read_custom_tags(
track_path: Path, album_fields: dict[str, Any], track_fields: dict[str, Any]
) -> None:
"""Read and set internally tracked fields."""
audio_file = mediafile.MediaFile(track_path)
album_fields["artist"] = audio_file.albumartist or audio_file.artist
album_fields["barcode"] = audio_file.barcode
if audio_file.catalognums is not None:
album_fields["catalog_nums"] = set(audio_file.catalognums)
album_fields["country"] = audio_file.country
album_fields["date"] = audio_file.date
album_fields["disc_total"] = audio_file.disctotal
album_fields["label"] = audio_file.label
album_fields["media"] = audio_file.media
album_fields["original_date"] = audio_file.original_date
album_fields["title"] = audio_file.album
album_fields["track_total"] = audio_file.tracktotal
track_fields["artist"] = audio_file.artist
if audio_file.artists is not None:
track_fields["artists"] = set(audio_file.artists)
track_fields["disc"] = audio_file.disc
if audio_file.genres is not None:
track_fields["genres"] = set(audio_file.genres)
track_fields["title"] = audio_file.title
track_fields["track_num"] = audio_file.track
class TrackError(LibraryError):
"""Error performing some operation on a Track."""
class MetaTrack(MetaLibItem):
"""A track containing only metadata.
It does not exist on the filesystem nor in the library. It can be used
to represent information about a track to later be merged into a full ``Track``
instance.
Attributes:
album (Optional[Album]): Corresponding Album object.
artist (Optional[str])
artists (Optional[set[str]]): Set of all artists.
custom (dict[str, Any]): Dictionary of custom fields.
disc (Optional[int]): Disc number the track is on.
genres (Optional[set[str]]): Set of all genres.
title (Optional[str])
track_num (Optional[int])
"""
def __init__(
self,
album: MetaAlbum,
track_num: int,
artist: Optional[str] = None,
artists: Optional[set[str]] = None,
disc: int = 1,
genres: Optional[set[str]] = None,
title: Optional[str] = None,
**kwargs,
):
"""Creates a MetaTrack object with any additional custom fields as kwargs."""
self.custom = kwargs
self.album = album
album.tracks.append(self)
self.track_num = track_num
self.artist = artist or self.album.artist
self.artists = artists
self.disc = disc
self.genres = genres
self.title = title
log.debug(f"MetaTrack created. [track={self!r}]")
@property
def genre(self) -> Optional[str]:
"""Returns a string of all genres concatenated with ';'."""
if self.genres is None:
return None
return ";".join(self.genres)
@genre.setter
def genre(self, genre_str: Optional[str]):
"""Sets a track's genre from a string.
Args:
genre_str: For more than one genre, they should be split with ';'.
"""
if genre_str is None:
self.genres = None
else:
self.genres = {genre.strip() for genre in genre_str.split(";")}
@property
def fields(self) -> set[str]:
"""Returns any editable, track-specific fields."""
return {
"album",
"artist",
"artists",
"disc",
"genres",
"title",
"track_num",
}
def merge(self, other: "MetaTrack", overwrite: bool = False):
"""Merges another track into this one.
Args:
other: Other track to be merged with the current track.
overwrite: Whether or not to overwrite self if a conflict exists.
"""
log.debug(
f"Merging tracks. [track_a={self!r}, track_b={other!r}, {overwrite=}]"
)
omit_fields = {"album"}
for field in self.fields - omit_fields:
other_value = getattr(other, field, None)
self_value = getattr(self, field, None)
if other_value and (overwrite or (not overwrite and not self_value)):
setattr(self, field, other_value)
for custom_field in self.custom:
other_value = other.custom.get(custom_field)
if other_value and (
overwrite or (not overwrite and not self.custom[custom_field])
):
self.custom[custom_field] = other_value
log.debug(f"Tracks merged. [track_a={self!r}, track_b={other!r}, {overwrite=}]")
def __eq__(self, other) -> bool:
"""Compares Tracks by their fields."""
if not isinstance(other, MetaTrack):
return False
for field in self.fields:
if not hasattr(other, field) or (
getattr(self, field) != getattr(other, field)
):
return False
return True
def __lt__(self, other) -> bool:
"""Sort based on album, then disc, then track number."""
if self.album == other.album:
if self.disc == other.disc:
return self.track_num < other.track_num
return self.disc < other.disc
return self.album < other.album
def __repr__(self):
"""Represents a Track using track-specific and relevant album fields."""
field_reprs = []
omit_fields = {"album"}
for field in self.fields - omit_fields:
if hasattr(self, field):
field_reprs.append(f"{field}={getattr(self, field)!r}")
repr_str = (
f"{type(self).__name__}("
+ ", ".join(field_reprs)
+ f", album='{self.album}'" # noqa: B907 album repr is too long
)
custom_field_reprs = []
for custom_field, value in self.custom.items():
custom_field_reprs.append(f"{custom_field}={value}")
if custom_field_reprs:
repr_str += ", custom_fields=[" + ", ".join(custom_field_reprs) + "]"
repr_str += ")"
return repr_str
def __str__(self):
"""String representation of a track."""
return f"{self.artist} - {self.title}"
class Track(LibItem, SABase, MetaTrack):
"""A single track in the library.
Attributes:
album (Album): Corresponding Album object.
artist (str)
artists (Optional[set[str]]): Set of all artists.
custom (dict[str, Any]): Dictionary of custom fields.
disc (int): Disc number the track is on.
genres (Optional[set[str]]): Set of all genres.
path (Path): Filesystem path of the track file.
title (str)
track_num (int)
Note:
Altering any album-related property attributes, will result in changing the
album field and thus all other tracks in the album as well.
"""
__tablename__ = "track"
artist: Mapped[str]
artists: Mapped[Optional[set[str]]] = mapped_column(
MutableSet.as_mutable(SetType()), nullable=True
)
disc: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
genres: Mapped[Optional[set[str]]] = mapped_column(
MutableSet.as_mutable(SetType()), nullable=True
)
title: Mapped[str]
track_num: Mapped[int]
custom: Mapped[dict[str, Any]] = mapped_column(
MutableDict.as_mutable(JSON(none_as_null=True)), default="{}", nullable=False
)
_album_id: Mapped[int] = mapped_column(Integer, ForeignKey("album._id"))
album: Mapped["Album"] = relationship(back_populates="tracks")
__table_args__ = (UniqueConstraint("disc", "track_num", "_album_id"),)
def __init__(
self,
album: Album,
path: Path,
title: str,
track_num: int,
artist: Optional[str] = None,
artists: Optional[set[str]] = None,
disc: Optional[int] = None,
genres: Optional[set[str]] = None,
**kwargs,
):
"""Creates a Track.
Args:
album: Album the track belongs to.
path: Filesystem path of the track file.
title: Title of the track.
track_num: Track number.
artist: Track artist. Defaults to the album artist if not given.
artists: Set of all artists.
disc: Disc the track belongs to. If not given, will try to guess the disc
based on the ``path`` of the track.
genres (Optional[set[str]]): Set of all genres.
**kwargs: Any custom fields to assign to the track.
"""
self.custom = kwargs
album.tracks.append(self)
self.path = path
self.artist = artist or self.album.artist
self.artists = artists
self.disc = disc or self._guess_disc()
self.genres = genres
self.title = title
self.track_num = track_num
log.debug(f"Track created. [track={self!r}]")
def _guess_disc(self) -> int:
"""Attempts to guess the disc of a track based on it's path."""
log.debug(f"Guessing track disc number. [track={self!r}]")
if self.path.parent == self.album.path:
return 1
# The track is in a subdirectory of the album - most likely disc directories.
disc_dirs: list[Path] = []
for path in self.album.path.iterdir():
if not path.is_dir():
continue
contains_tracks = False
for album_track in self.album.tracks:
if album_track.path.is_relative_to(path):
contains_tracks = True
if contains_tracks:
disc_dirs.append(path)
# Guess the disc by the order of the disc directory it appears in.
for disc_num, disc_dir in enumerate(sorted(disc_dirs), start=1):
if self.path.is_relative_to(disc_dir):
return disc_num
return 1
@classmethod
def from_file(cls, track_path: Path, album: Optional[Album] = None) -> "Track":
"""Alternate initializer that creates a Track from a track file.
Will read any tags from the given path and save them to the Track.
Args:
track_path: Filesystem path of the track.
album: Corresponding album for the track. If not given, the album will be
created.
Returns:
Track instance.
Raises:
TrackError: Given ``path`` does not correspond to a track file.
ValueError: Track is missing required fields.
"""
log.debug(f"Creating track from path. [path={track_path}, {album=}]")
try:
mediafile.MediaFile(track_path)
except mediafile.UnreadableFileError as err:
raise TrackError(
"Unable to create track; given path is not a track file. "
f"[path={track_path}]"
) from err
album_fields: dict[str, Any] = {}
track_fields: dict[str, Any] = {}
config.CONFIG.pm.hook.read_custom_tags(
track_path=track_path, album_fields=album_fields, track_fields=track_fields
)
title = track_fields.pop("title")
track_num = track_fields.pop("track_num")
album_artist = album_fields.pop("artist")
album_title = album_fields.pop("title")
date = album_fields.pop("date")
disc_total = album_fields.pop("disc_total") or 1
missing_reqd_fields = []
if not title:
missing_reqd_fields.append("title")
if not track_num:
missing_reqd_fields.append("track_num")
if not album_artist and not album:
missing_reqd_fields.append("album_artist")
if not album_title and not album:
missing_reqd_fields.append("album_title")
if not date and not album:
missing_reqd_fields.append("date")
if missing_reqd_fields:
raise ValueError(
f"Track is missing required fields. [{missing_reqd_fields=}]"
)
if not album:
album = Album(
path=track_path.parent,
artist=album_artist,
title=album_title,
date=date,
disc_total=disc_total,
**album_fields,
)
return cls(
album=album,
path=track_path,
title=title,
track_num=track_num,
**track_fields,
)
@property
def audio_format(self) -> str:
"""Returns the audio format of the track.
One of ['aac', 'aiff', 'alac', 'ape', 'asf', 'dsf', 'flac', 'ogg', 'opus',
'mp3', 'mpc', 'wav', 'wv'].
"""
return mediafile.MediaFile(self.path).type
@property
def bit_depth(self) -> int:
"""Returns the number of bits per sample in the audio encoding.
The bit depth is an integer and zero when unavailable or when the file format
does not support bit depth.
"""
return mediafile.MediaFile(self.path).bitdepth
@property
def fields(self) -> set[str]:
"""Returns any editable, track-specific fields."""
return super().fields.union({"path"})
@property
def sample_rate(self) -> int:
"""Returns the sampling rate of the track.
The sampling rate is in Hertz (Hz) as an integer and zero when unavailable.
"""
return mediafile.MediaFile(self.path).samplerate
def is_unique(self, other: "Track") -> bool:
"""Returns whether a track is unique in the library from ``other``."""
if self.path == other.path:
return False
if (
self.track_num == other.track_num
and self.disc == other.disc
and self.album == other.album
):
return False
custom_uniqueness = config.CONFIG.pm.hook.is_unique_track(
track=self, other=other
)
if False in custom_uniqueness:
return False
return True