Coverage for downtify/library_metadata.py: 78%
188 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""Read embedded audio tags for library / player display."""
3from __future__ import annotations
5from pathlib import Path
6from typing import Any
8from mutagen import File as MutagenFile
9from mutagen.id3 import ID3
10from mutagen.mp4 import MP4
12from .album_artist import is_act_of
13from .content_advisory import (
14 ADVISORY_TAG,
15 EXPLICIT_VALUES,
16 MP4_ADVISORY_ATOM,
17)
18from .cover_art import extract_cover_art
19from .image_size import image_short_side
20from .isrc import read as read_isrc
23def _tag_text(value: Any) -> str:
24 if value is None:
25 return ''
26 if isinstance(value, list):
27 parts = [_tag_text(item) for item in value]
28 return '; '.join(part for part in parts if part)
29 return str(value).strip()
32def split_artists(artist: str, album_artist: str = '') -> list[str]:
33 """The artists in an artist tag's text, for a file with no ``ARTISTS``
34 tag: split on the first of ``;`` (how Downtify joins them in MP3 and
35 how a multi-value tag reads back), `` / `` or ``, `` it contains - the
36 web app's own rule (``frontend/src/lib/library.js``). ``AC/DC`` stays
37 whole, and so does a text that is the file's *album_artist* too
38 (``Earth, Wind & Fire`` on its own album): that is one name.
40 So is a split whose names make up the album artist: an act YouTube
41 Music credited as its members, which older Downtify versions wrote as
42 ``Henrique; Juliano`` on an album by ``Henrique, Juliano`` - one act,
43 named as its album is."""
45 text = str(artist or '').strip()
46 if not text:
47 return []
48 album_artist = str(album_artist or '').strip()
49 if text.casefold() == album_artist.casefold():
50 return [text]
51 for sep in (';', ' / ', ', '):
52 if sep in text:
53 parts = [part.strip() for part in text.split(sep) if part.strip()]
54 if is_act_of(parts, album_artist):
55 return [album_artist]
56 return parts
57 return [text]
60def _multi_value_artists(path: Path, audio: Any) -> list[str]:
61 """The ``ARTISTS`` tag - one artist per value, as Downtify and
62 MusicBrainz Picard write it - or ``[]`` when the file has none."""
64 suffix = path.suffix.lower()
65 try:
66 if suffix == '.mp3':
67 frame = ID3(str(path)).get('TXXX:ARTISTS')
68 values = list(frame.text) if frame is not None else []
69 elif suffix in {'.m4a', '.mp4', '.aac'}:
70 tags = MP4(str(path)).tags or {}
71 values = [
72 bytes(value).decode('utf-8', 'replace')
73 for value in tags.get('----:com.apple.iTunes:ARTISTS', [])
74 ]
75 else:
76 tags = getattr(audio, 'tags', None)
77 values = list(tags.get('artists') or []) if tags else []
78 except Exception:
79 return []
80 return [str(value).strip() for value in values if str(value).strip()]
83def _track_number(value: Any) -> int:
84 """``3``, ``'3'`` or ``'3/12'`` -> 3; anything unreadable -> 0."""
86 text = _tag_text(value).split('/', 1)[0].strip()
87 try:
88 return max(0, int(text))
89 except ValueError:
90 return 0
93def _year(value: Any) -> str:
94 text = _tag_text(value)
95 return text[:4] if len(text) >= 4 and text[:4].isdigit() else ''
98def _duration(audio: Any) -> float:
99 try:
100 length = float(audio.info.length)
101 except (AttributeError, TypeError, ValueError):
102 return 0.0
103 return round(length, 2) if length > 0 else 0.0
106def _codec(audio: Any) -> str:
107 """The audio codec, in the names a client knows: ``mp3``, ``flac``,
108 ``aac``, ``alac``, ``opus``, ``vorbis`` - ``''`` when unknown."""
110 kind = type(audio).__name__.lower()
111 if kind in {'mp3', 'easymp3'}:
112 return 'mp3'
113 if kind == 'flac':
114 return 'flac'
115 if kind in {'oggopus'}:
116 return 'opus'
117 if kind in {'oggvorbis'}:
118 return 'vorbis'
119 if kind in {'mp4', 'easymp4'}:
120 codec = str(getattr(audio.info, 'codec', '') or '').lower()
121 if codec.startswith('mp4a'):
122 return 'aac'
123 return codec or 'aac'
124 return ''
127def audio_format(audio: Any) -> dict[str, Any]:
128 """``codec``, ``bitrate`` (bits/s), ``sample_rate`` (Hz) and
129 ``channels`` of a mutagen file; zeros and ``''`` when unknown."""
131 info = getattr(audio, 'info', None)
133 def number(name: str) -> int:
134 try:
135 return max(0, int(getattr(info, name, 0) or 0))
136 except (TypeError, ValueError):
137 return 0
139 return {
140 'codec': _codec(audio) if audio is not None else '',
141 'bitrate': number('bitrate'),
142 'sample_rate': number('sample_rate'),
143 'channels': number('channels'),
144 }
147def read_explicit(path: Path) -> bool:
148 """Whether the file is marked explicit: an ``ITUNESADVISORY`` text
149 (ID3 TXXX frame, Vorbis/FLAC/Opus comment) or an MP4 ``rtng`` atom."""
151 try:
152 if path.suffix.lower() == '.mp3':
153 frames = ID3(str(path)).getall('TXXX')
154 values = [
155 str(text)
156 for frame in frames
157 if str(frame.desc).upper() == ADVISORY_TAG
158 for text in frame.text
159 ]
160 else:
161 audio = MutagenFile(str(path))
162 tags = audio.tags if audio is not None else None
163 if tags is None:
164 return False
165 raw = tags.get(MP4_ADVISORY_ATOM) or tags.get(ADVISORY_TAG)
166 values = [str(item) for item in (raw or [])]
167 except Exception:
168 return False
169 return any(value.strip() in EXPLICIT_VALUES for value in values)
172def read_compilation(path: Path) -> bool:
173 """Whether the file carries the compilation flag Downtify writes on a
174 various-artists compilation's tracks (and taggers like Picard do): ID3
175 ``TCMP``, MP4 ``cpil`` or a Vorbis/FLAC/Opus ``COMPILATION`` comment."""
177 try:
178 if path.suffix.lower() == '.mp3':
179 frame = ID3(str(path)).get('TCMP')
180 values = [str(text) for text in (frame.text if frame else [])]
181 else:
182 audio = MutagenFile(str(path))
183 tags = audio.tags if audio is not None else None
184 if tags is None:
185 return False
186 raw = tags.get('cpil')
187 if raw is None:
188 raw = tags.get('compilation') or tags.get('COMPILATION')
189 if isinstance(raw, bool):
190 return raw
191 values = [str(item) for item in (raw or [])]
192 except Exception:
193 return False
194 return any(value.strip() in {'1', 'True', 'true'} for value in values)
197def read_audio_metadata(path: Path) -> dict[str, Any]:
198 """Return display tags read from ``path``.
200 ``title``, ``artist``, ``artists`` and ``album``, plus
201 ``album_artist``, ``track_number`` (0 when unknown), ``year`` and
202 ``duration`` in seconds (0 when unknown), plus the audio format:
203 ``codec``, ``bitrate``, ``sample_rate`` and ``channels`` (see
204 :func:`audio_format`), ``explicit`` (:func:`read_explicit`),
205 ``compilation`` (:func:`read_compilation`) and ``isrc`` (the
206 recording's code, ``''`` without one - see :mod:`downtify.isrc`).
207 """
209 empty: dict[str, Any] = {
210 'title': '',
211 'artist': '',
212 'artists': [],
213 'album': '',
214 'album_artist': '',
215 'track_number': 0,
216 'year': '',
217 'release_date': '',
218 'genre': '',
219 'duration': 0.0,
220 'explicit': False,
221 'compilation': False,
222 'isrc': '',
223 **audio_format(None),
224 }
225 if not path.is_file():
226 return dict(empty)
228 title = ''
229 artist = ''
230 album = ''
231 album_artist = ''
232 track_number = 0
233 year = ''
234 release_date = ''
235 genre = ''
236 duration = 0.0
238 try:
239 audio = MutagenFile(str(path), easy=True)
240 except Exception:
241 audio = None
242 fmt = audio_format(audio)
244 if audio is not None:
245 title = _tag_text(audio.get('title'))
246 artist = _tag_text(audio.get('artist'))
247 album = _tag_text(audio.get('album'))
248 album_artist = _tag_text(audio.get('albumartist'))
249 track_number = _track_number(audio.get('tracknumber'))
250 release_date = _tag_text(audio.get('date'))
251 year = _year(release_date)
252 genre = _tag_text(audio.get('genre'))
253 duration = _duration(audio)
255 if not title and audio.tags is not None:
256 title = _tag_text(audio.tags.get('title'))
257 if not artist and audio.tags is not None:
258 artist = _tag_text(audio.tags.get('artist'))
259 if not album and audio.tags is not None:
260 album = _tag_text(audio.tags.get('album'))
262 if not title and not artist and not album:
263 try:
264 id3 = ID3(str(path))
265 except Exception:
266 id3 = None
267 if id3 is not None:
268 title = _tag_text(id3.get('TIT2'))
269 artist = _tag_text(id3.get('TPE1'))
270 album = _tag_text(id3.get('TALB'))
271 album_artist = _tag_text(id3.get('TPE2'))
272 track_number = _track_number(id3.get('TRCK'))
273 release_date = _tag_text(id3.get('TDRC'))
274 year = _year(release_date)
275 genre = _tag_text(id3.get('TCON'))
277 artists = _multi_value_artists(path, audio) or split_artists(
278 artist, album_artist
279 )
280 return {
281 'title': title,
282 'artist': artist,
283 'artists': artists,
284 'album': album,
285 'album_artist': album_artist,
286 'track_number': track_number,
287 'year': year,
288 'release_date': release_date,
289 'genre': genre,
290 'duration': duration,
291 'explicit': read_explicit(path),
292 'compilation': read_compilation(path),
293 'isrc': read_isrc(path),
294 **fmt,
295 }
298def file_stat_fields(full_path: Path) -> dict[str, int]:
299 """``added`` (modification time, epoch seconds) and ``size`` in bytes."""
301 try:
302 st = full_path.stat()
303 except OSError:
304 return {'added': 0, 'size': 0}
305 return {'added': int(st.st_mtime), 'size': int(st.st_size)}
308def library_entry_for_file(
309 stored_path: str, full_path: Path
310) -> dict[str, Any]:
311 """Build one ``/tracks`` row using tags, then filename fallbacks."""
313 fb_title, fb_artist = _fallback_title_from_filename(full_path)
314 meta = read_audio_metadata(full_path)
315 title = str(meta.get('title') or '').strip() or fb_title
316 artist = str(meta.get('artist') or '').strip() or fb_artist
317 artists = [
318 str(name).strip()
319 for name in meta.get('artists') or []
320 if str(name).strip()
321 ] or split_artists(artist, str(meta.get('album_artist') or ''))
322 album = str(meta.get('album') or '').strip()
323 # The cover is read once and both answered from it: whether there is
324 # one, and how big it is (which the library upgrade scan needs for
325 # every track, and would otherwise pay a second full read for).
326 cover_data, _cover_mime = (
327 extract_cover_art(full_path) if full_path.is_file() else (None, None)
328 )
329 return {
330 'file': stored_path,
331 'title': title,
332 'artist': artist,
333 # Every credited artist, one per entry (see read_audio_metadata).
334 'artists': artists,
335 'album': album,
336 'album_artist': str(meta.get('album_artist') or '').strip(),
337 'track_number': int(meta.get('track_number') or 0),
338 'year': str(meta.get('year') or ''),
339 'release_date': str(meta.get('release_date') or ''),
340 'genre': str(meta.get('genre') or ''),
341 'duration': float(meta.get('duration') or 0.0),
342 'codec': str(meta.get('codec') or ''),
343 'bitrate': int(meta.get('bitrate') or 0),
344 'sample_rate': int(meta.get('sample_rate') or 0),
345 'channels': int(meta.get('channels') or 0),
346 'explicit': bool(meta.get('explicit')),
347 'compilation': bool(meta.get('compilation')),
348 'isrc': str(meta.get('isrc') or ''),
349 'has_cover': bool(cover_data),
350 'cover_px': image_short_side(cover_data),
351 **file_stat_fields(full_path),
352 }
355def _fallback_title_from_filename(path: Path) -> tuple[str, str]:
356 """Parse ``Artist - Title`` from the basename when tags are missing."""
358 stem = path.stem
359 dash = stem.find(' - ')
360 if dash > 0:
361 return stem[dash + 3 :].strip(), stem[:dash].strip()
362 return stem, ''