Coverage for downtify/lyrics.py: 82%
553 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"""Lyrics providers used to enrich downloaded audio files.
3Three sources are implemented, all free and keyless: ``lrclib``
4(https://lrclib.net), ``netease`` (NetEase Cloud Music) and ``kugou``
5(Kugou Music's lyrics service). Users put them in the order they prefer;
6:func:`fetch` walks that order and stops at the first provider that has
7something - with ``synced_only``, at the first that has time-synced
8lyrics.
10The legacy ``genius``/``musixmatch``/``azlyrics`` identifiers from the
11spotdl-era UI are accepted as no-ops so existing settings keep
12round-tripping cleanly. They are not implemented: AZLyrics forbids
13third-party use of its content, Musixmatch's desktop API hands out an
14empty token without credentials, and Genius' robots.txt disallows the
15search endpoint needed to find a song's page.
16"""
18from __future__ import annotations
20import base64
21import binascii
22import os
23import re
24import unicodedata
25from collections.abc import Sequence
26from dataclasses import dataclass
27from pathlib import Path
28from typing import Any, Callable, Optional
30import httpx
31from loguru import logger
32from mutagen import File as MutagenFile
33from mutagen.flac import FLAC
34from mutagen.id3 import ID3, SYLT, USLT
35from mutagen.mp3 import MP3
36from mutagen.mp4 import MP4, MP4Tags
37from mutagen.oggopus import OggOpus
38from mutagen.oggvorbis import OggVorbis
40from .library_paths import library_stored_path
41from .lyrics_cache import song_key
43LRCLIB_BASE = 'https://lrclib.net/api'
44NETEASE_BASE = 'https://music.163.com/api'
45KUGOU_BASE = 'https://lyrics.kugou.com'
46_USER_AGENT = 'Downtify (https://github.com/henriquesebastiao/downtify)'
47_TIMEOUT = 10
49#: Implemented providers, in the order they are offered by default.
50PROVIDER_ORDER = ['lrclib', 'netease', 'kugou']
51SUPPORTED_PROVIDERS = set(PROVIDER_ORDER)
52#: Accepted in saved settings, but nothing is fetched from them.
53LEGACY_PROVIDERS = {'genius', 'musixmatch', 'azlyrics'}
55DEFAULT_LYRICS_LRC_DIR = '/data/lyrics'
56MAX_LYRICS_LRC_DIR_LEN = 1024
58_LrcResolve = Callable[[Path], Path]
59_LrcRoot = Callable[[], Optional[Path]]
60_LrcSearch = Callable[[Path], Sequence[Path]]
61_lrc_resolve: Optional[_LrcResolve] = None
62_lrc_tree_root: Optional[_LrcRoot] = None
63_lrc_search: Optional[_LrcSearch] = None
66def set_lrc_resolver(
67 resolve: Optional[_LrcResolve],
68 *,
69 tree_root: Optional[_LrcRoot] = None,
70 search: Optional[_LrcSearch] = None,
71) -> None:
72 """Hook used by the API to place ``.lrc`` files from live settings."""
74 global _lrc_resolve, _lrc_tree_root, _lrc_search
75 _lrc_resolve = resolve
76 _lrc_tree_root = tree_root
77 _lrc_search = search
80def lrc_tree_root() -> Optional[Path]:
81 """Dedicated lyrics folder when sidecars are not kept beside audio."""
83 if _lrc_tree_root is None:
84 return None
85 try:
86 return _lrc_tree_root()
87 except Exception:
88 logger.opt(exception=True).debug('LRC tree root lookup failed')
89 return None
92def coerce_bool(value: Any, default: bool = True) -> bool:
93 if isinstance(value, bool):
94 return value
95 if isinstance(value, str):
96 lowered = value.strip().lower()
97 if lowered in {'1', 'true', 'yes', 'on'}:
98 return True
99 if lowered in {'0', 'false', 'no', 'off', ''}:
100 return False
101 return default
102 if isinstance(value, (int, float)):
103 return bool(value)
104 return default
107def _path_inside(path: Path, root: Path) -> bool:
108 try:
109 path.relative_to(root)
110 except ValueError:
111 return False
112 return True
115def sanitize_lyrics_lrc_dir(
116 raw: Any,
117 *,
118 download_dir: Path,
119 slskd_dir: Optional[Path] = None,
120 extra_dirs: Optional[Sequence[Path]] = None,
121) -> str:
122 """Absolute lyrics tree that is not inside a music folder."""
124 text = str(raw or '').strip()
125 if not text or len(text) > MAX_LYRICS_LRC_DIR_LEN:
126 return DEFAULT_LYRICS_LRC_DIR
127 path = Path(text)
128 if not path.is_absolute():
129 return DEFAULT_LYRICS_LRC_DIR
130 try:
131 resolved = path.resolve()
132 except OSError:
133 resolved = path
134 if resolved == Path('/') or len(resolved.parts) < 2:
135 return DEFAULT_LYRICS_LRC_DIR
136 forbidden: list[Path] = [download_dir]
137 if slskd_dir is not None:
138 forbidden.append(slskd_dir)
139 forbidden.extend(extra_dirs or ())
140 for root in forbidden:
141 try:
142 root_resolved = root.resolve()
143 except OSError:
144 root_resolved = root
145 if _path_inside(resolved, root_resolved):
146 return DEFAULT_LYRICS_LRC_DIR
147 return str(path)
150def lrc_sidecar_path(
151 audio: Path,
152 *,
153 settings: dict[str, Any],
154 download_dir: Path,
155 slskd_dir: Optional[Path] = None,
156 extra_dirs: Optional[Sequence[Path]] = None,
157) -> Path:
158 """Where the ``.lrc`` for *audio* should live given *settings*."""
160 if coerce_bool(settings.get('lyrics_lrc_beside'), True):
161 return audio.with_suffix('.lrc')
162 root = Path(str(settings.get('lyrics_lrc_dir') or DEFAULT_LYRICS_LRC_DIR))
163 stored = library_stored_path(audio, download_dir, slskd_dir, extra_dirs)
164 return (root / stored).with_suffix('.lrc')
167def lrc_path_for(audio: Path, sidecar: Optional[Path] = None) -> Path:
168 """Sidecar path for *audio*, honouring the live settings hook."""
170 if sidecar is not None:
171 return sidecar
172 if _lrc_resolve is not None:
173 try:
174 return _lrc_resolve(audio)
175 except Exception:
176 logger.opt(exception=True).debug(
177 'LRC path resolver failed for {}', audio
178 )
179 return audio.with_suffix('.lrc')
182def lrc_candidates(audio: Path) -> list[Path]:
183 """Possible sidecar locations (configured dest, beside, and extras)."""
185 dest = lrc_path_for(audio)
186 beside = audio.with_suffix('.lrc')
187 extra: list[Path] = []
188 if _lrc_search is not None:
189 try:
190 extra = [Path(item) for item in (_lrc_search(audio) or ())]
191 except Exception:
192 logger.opt(exception=True).debug(
193 'LRC search paths failed for {}', audio
194 )
195 found: list[Path] = []
196 for path in (dest, beside, *extra):
197 if path not in found:
198 found.append(path)
199 return found
202def can_mutate_audio(path: Path) -> bool:
203 """False when *path* (or its folder) cannot be rewritten in place.
205 Extra folders mounted read-only still yield tags and a dedicated
206 ``.lrc``; they must not be tagged or have leftover sidecars deleted.
207 """
209 try:
210 parent = path.parent
211 if not os.access(parent, os.W_OK):
212 return False
213 if path.exists() and not os.access(path, os.W_OK):
214 return False
215 except OSError:
216 return False
217 return True
220def relocate_lrc_sidecar(audio: Path) -> str:
221 """Put the sidecar at the configured location.
223 ``present`` — already there; ``copied`` — moved from the other place;
224 ``missing`` — nothing to copy.
225 """
227 dest = lrc_path_for(audio)
228 try:
229 if dest.is_file() and dest.stat().st_size:
230 _unlink_other_lrc(audio, dest)
231 return 'present'
232 except OSError:
233 pass
234 for candidate in lrc_candidates(audio):
235 if candidate == dest:
236 continue
237 try:
238 if not candidate.is_file():
239 continue
240 text = candidate.read_text(encoding='utf-8').strip()
241 except (OSError, UnicodeDecodeError):
242 continue
243 if not text:
244 continue
245 try:
246 dest.parent.mkdir(parents=True, exist_ok=True)
247 dest.write_text(text, encoding='utf-8')
248 except OSError:
249 logger.opt(exception=True).warning(
250 'Could not write LRC sidecar {}', dest
251 )
252 continue
253 _unlink_other_lrc(audio, dest)
254 return 'copied'
255 return 'missing'
258def _unlink_other_lrc(audio: Path, dest: Path) -> None:
259 for leftover in lrc_candidates(audio):
260 if leftover == dest:
261 continue
262 if leftover.exists() and not can_mutate_audio(leftover):
263 logger.debug('Leaving LRC on read-only tree {}', leftover)
264 continue
265 try:
266 leftover.unlink(missing_ok=True)
267 except OSError:
268 logger.opt(exception=True).debug(
269 'Could not remove old LRC sidecar {}', leftover
270 )
273_LRC_STAMP = re.compile(r'\[\d{1,2}:\d{2}')
276def looks_like_lrc(text: str) -> bool:
277 """True when *text* already carries LRC timestamps."""
279 return bool(text and _LRC_STAMP.search(text))
282@dataclass
283class Lyrics:
284 plain: Optional[str] = None
285 synced: Optional[str] = None
287 def has_any(self) -> bool:
288 return bool(self.plain) or bool(self.synced)
290 def usable(self, synced_only: bool = False) -> bool:
291 """Whether this is worth keeping: anything at all, or only
292 time-synced lyrics when *synced_only*."""
294 return bool(self.synced) if synced_only else self.has_any()
297def providers_from_settings(settings: dict[str, Any]) -> list[str]:
298 """Providers a download (and library sync) will try, in order.
300 Unknown names are dropped; a list left with nothing but the spotdl-era
301 placeholders (genius/musixmatch/azlyrics) falls back to the defaults,
302 since those settings were never asking for "no lyrics". An explicitly
303 empty list, and lyrics being off, both mean none.
304 """
306 if not settings.get('download_lyrics', True):
307 return []
308 raw = [
309 part.strip()
310 for part in (settings.get('lyrics_providers') or [])
311 if isinstance(part, str) and part.strip()
312 ]
313 if not raw:
314 return []
315 providers: list[str] = []
316 for name in raw:
317 if name in SUPPORTED_PROVIDERS and name not in providers:
318 providers.append(name)
319 return providers or list(PROVIDER_ORDER)
322def fetch(
323 song: dict[str, Any],
324 providers: list[str],
325 cache: Optional[Any] = None,
326 *,
327 synced_only: bool = False,
328) -> Optional[Lyrics]:
329 """Try each provider in order; return the first successful match.
331 ``cache`` is an optional :class:`~downtify.lyrics_cache.LyricsLookupCache`:
332 providers that recently came back empty for this song are skipped, and
333 every answer is recorded. With *synced_only*, lyrics without
334 timestamps count as nothing: the next provider is asked.
335 """
337 key = song_key(song) if cache is not None else ''
338 for name in providers:
339 if name not in SUPPORTED_PROVIDERS:
340 continue
341 if cache is not None and cache.should_skip(key, name):
342 logger.debug('Lyrics: skipping {} (nothing last time)', name)
343 continue
344 try:
345 result = _PROVIDER_FNS[name](song)
346 except Exception:
347 logger.exception('Lyrics provider {!r} failed', name)
348 continue
349 found = bool(result and result.usable(synced_only))
350 if cache is not None:
351 cache.record(key, name, found)
352 if found:
353 if name != providers[0]:
354 logger.info(
355 'Lyrics for {!r} came from {}', song.get('name'), name
356 )
357 return result
358 return None
361def _fetch_lrclib(song: dict[str, Any]) -> Optional[Lyrics]:
362 artists = song.get('artists') or []
363 title = (song.get('name') or '').strip()
364 if not title or not artists:
365 return None
367 params = {
368 'track_name': title,
369 'artist_name': artists[0],
370 }
371 album = (song.get('album_name') or '').strip()
372 if album:
373 params['album_name'] = album
374 duration = song.get('duration') or 0
375 if duration:
376 params['duration'] = int(duration)
378 try:
379 response = httpx.get(
380 f'{LRCLIB_BASE}/get',
381 params=params,
382 headers={'User-Agent': _USER_AGENT},
383 timeout=10,
384 )
385 except httpx.RequestError:
386 logger.opt(exception=True).warning('lrclib request failed')
387 return None
389 if response.status_code == 404:
390 return None
391 if response.status_code != 200:
392 logger.warning(
393 'lrclib returned HTTP {} for {!r}', response.status_code, title
394 )
395 return None
397 try:
398 data = response.json()
399 except ValueError:
400 return None
402 found = _lrclib_lyrics(data)
403 if found is not None and found.synced:
404 return found
405 # No exact match, or one without timestamps: LRCLIB's search finds
406 # the same song filed under a slightly different album or length.
407 searched = _search_lrclib(song)
408 return searched or found
411def _lrclib_lyrics(data: Any) -> Optional[Lyrics]:
412 if not isinstance(data, dict):
413 return None
414 plain = (data.get('plainLyrics') or '').strip() or None
415 synced = (data.get('syncedLyrics') or '').strip() or None
416 if not plain and not synced:
417 return None
418 return Lyrics(plain=plain, synced=synced)
421def _search_lrclib(song: dict[str, Any]) -> Optional[Lyrics]:
422 """The best time-synced hit of LRCLIB's search for the song, matched
423 on title, artist and length the way NetEase hits are."""
425 artists = song.get('artists') or []
426 title = (song.get('name') or '').strip()
427 artist = str(artists[0] if artists else '').strip()
428 if not title or not artist:
429 return None
430 try:
431 response = httpx.get(
432 f'{LRCLIB_BASE}/search',
433 params={'track_name': title, 'artist_name': artist},
434 headers={'User-Agent': _USER_AGENT},
435 timeout=_TIMEOUT,
436 )
437 except httpx.RequestError:
438 logger.opt(exception=True).warning('lrclib search failed')
439 return None
440 if response.status_code != 200:
441 return None
442 try:
443 hits = response.json()
444 except ValueError:
445 return None
446 duration = float(song.get('duration') or 0)
447 best = None
448 best_score = 0.0
449 for hit in hits if isinstance(hits, list) else []:
450 if not isinstance(hit, dict) or not hit.get('syncedLyrics'):
451 continue
452 candidate = {
453 'name': hit.get('trackName') or hit.get('name'),
454 'artists': [{'name': hit.get('artistName')}],
455 'duration': float(hit.get('duration') or 0) * 1000,
456 }
457 score = _netease_score(candidate, title, artist, duration)
458 if score > best_score:
459 best, best_score = hit, score
460 return _lrclib_lyrics(best) if best is not None else None
463# ── NetEase Cloud Music ──────────────────────────────────────────────
464# Its public search and lyric endpoints need no key. Lyrics come as LRC,
465# so synced and plain text both fall out of one request.
467#: Credits NetEase puts inside the lyric body ("作词 : ..."), dropped so
468#: they don't end up in the tag or the .lrc file.
469_NETEASE_CREDIT = re.compile(
470 r'^(作词|作曲|编曲|制作人|录音|混音|母带|监制|出品|发行|词|曲|'
471 r'lyricist|composer|arranger|producer|mixing|mastering|'
472 r'written by|lyrics by|music by|composed by|produced by)\s*[::]',
473 re.IGNORECASE,
474)
475#: NetEase marks instrumentals with this instead of leaving lyrics empty.
476_NETEASE_INSTRUMENTAL = '纯音乐'
477_LRC_LINE = re.compile(r'^((?:\[\d{1,3}:\d{2}(?:[.:]\d{1,3})?\])+)(.*)$')
480def _normalize(text: Any) -> str:
481 text = unicodedata.normalize('NFKC', str(text or '')).casefold()
482 return re.sub(r'[^\w\s]', ' ', text).strip()
485def _netease_get(path: str, params: dict[str, Any]) -> Optional[dict]:
486 try:
487 response = httpx.get(
488 f'{NETEASE_BASE}{path}',
489 params=params,
490 headers={
491 'User-Agent': _USER_AGENT,
492 'Referer': 'https://music.163.com/',
493 },
494 timeout=_TIMEOUT,
495 )
496 except httpx.RequestError:
497 logger.opt(exception=True).warning('NetEase request failed')
498 return None
499 if response.status_code != 200:
500 logger.warning('NetEase returned HTTP {}', response.status_code)
501 return None
502 try:
503 return response.json()
504 except ValueError:
505 return None
508def _core_title(text: Any) -> str:
509 """Title without the bracketed extras services add or drop.
511 YouTube Music may call a song "起风了(The Wind)" where NetEase has
512 just "起风了"; comparing the part before the brackets matches them.
513 """
515 stripped = re.sub(r'[(\[][^)\]]*[)\]]', ' ', _normalize(text))
516 return re.sub(r'\s+', ' ', stripped).strip()
519def _netease_score(
520 candidate: dict[str, Any], title: str, artist: str, duration: float
521) -> float:
522 """How well a search hit matches the song (higher is better, <0 rejects)."""
524 name = _core_title(candidate.get('name'))
525 wanted_title = _core_title(title)
526 if not name or not wanted_title:
527 return -1
528 if name == wanted_title:
529 score = 2.0
530 elif wanted_title in name or name in wanted_title:
531 score = 1.0
532 else:
533 return -1
535 artists = [
536 _normalize(a.get('name'))
537 for a in (candidate.get('artists') or [])
538 if isinstance(a, dict)
539 ]
540 wanted_artist = _normalize(artist)
541 artist_matched = bool(wanted_artist) and any(
542 wanted_artist == a or wanted_artist in a or a in wanted_artist
543 for a in artists
544 )
545 if artist_matched:
546 score += 2 if wanted_artist in artists else 1
548 delta = None
549 if duration:
550 # NetEase reports milliseconds.
551 delta = abs(float(candidate.get('duration') or 0) / 1000 - duration)
552 if delta > 15:
553 return -1
554 score += max(0.0, 1 - delta / 15)
556 # Services write artists differently ("馮沁苑LaJiao" vs
557 # "冯沁苑(买辣椒也用券)"), so a name that doesn't line up is only
558 # accepted when the title and the length both do.
559 if not artist_matched and (delta is None or delta > 3):
560 return -1
561 return score
564def _parse_lrc(text: str) -> Lyrics:
565 """LRC text → timed lines (synced) and their words (plain)."""
567 synced: list[str] = []
568 plain: list[str] = []
569 for raw in text.splitlines():
570 line = raw.strip()
571 if not line:
572 continue
573 match = _LRC_LINE.match(line)
574 words = (match.group(2) if match else line).strip()
575 if _NETEASE_CREDIT.match(words):
576 continue
577 if match:
578 synced.append(f'{match.group(1)}{words}')
579 if words:
580 plain.append(words)
581 return Lyrics(
582 plain='\n'.join(plain).strip() or None,
583 synced='\n'.join(synced).strip() or None,
584 )
587def _fetch_netease(song: dict[str, Any]) -> Optional[Lyrics]:
588 artists = song.get('artists') or []
589 title = (song.get('name') or '').strip()
590 artist = str(artists[0] if artists else '').strip()
591 if not title:
592 return None
594 data = _netease_get(
595 '/search/get',
596 {
597 's': f'{artist} {title}'.strip(),
598 'type': 1,
599 'limit': 8,
600 'offset': 0,
601 },
602 )
603 songs = ((data or {}).get('result') or {}).get('songs') or []
604 duration = float(song.get('duration') or 0)
605 best = None
606 best_score = 0.0
607 for candidate in songs:
608 if not isinstance(candidate, dict):
609 continue
610 score = _netease_score(candidate, title, artist, duration)
611 if score > best_score:
612 best, best_score = candidate, score
613 if best is None:
614 return None
616 lyric = _netease_get(
617 '/song/lyric', {'id': best.get('id'), 'lv': 1, 'kv': 1, 'tv': -1}
618 )
619 if not lyric or lyric.get('nolyric') or lyric.get('uncollected'):
620 return None
621 text = ((lyric.get('lrc') or {}).get('lyric') or '').strip()
622 if not text or _NETEASE_INSTRUMENTAL in text:
623 return None
624 result = _parse_lrc(text)
625 return result if result.has_any() else None
628# ── Kugou ────────────────────────────────────────────────────────────
629# Kugou Music's lyrics service: a keyless search that lists candidate
630# lyrics with their song's length, then the chosen one as base64 LRC.
632#: LRC header tags (``[ar:Artist]``, ``[offset:0]``): not lyrics.
633_LRC_TAG = re.compile(r'^\[[a-z#]+:[^\]]*\]$', re.IGNORECASE)
636def _kugou_get(path: str, params: dict[str, Any]) -> Optional[dict]:
637 try:
638 response = httpx.get(
639 f'{KUGOU_BASE}{path}',
640 params=params,
641 headers={'User-Agent': _USER_AGENT},
642 timeout=_TIMEOUT,
643 )
644 except httpx.RequestError:
645 logger.opt(exception=True).warning('Kugou request failed')
646 return None
647 if response.status_code != 200:
648 logger.warning('Kugou returned HTTP {}', response.status_code)
649 return None
650 try:
651 data = response.json()
652 except ValueError:
653 return None
654 return data if isinstance(data, dict) else None
657def _fetch_kugou(song: dict[str, Any]) -> Optional[Lyrics]:
658 artists = song.get('artists') or []
659 title = (song.get('name') or '').strip()
660 artist = str(artists[0] if artists else '').strip()
661 if not title:
662 return None
663 duration = float(song.get('duration') or 0)
664 data = _kugou_get(
665 '/search',
666 {
667 'ver': 1,
668 'man': 'yes',
669 'client': 'pc',
670 'keyword': f'{artist} - {title}' if artist else title,
671 'duration': int(duration * 1000) if duration else '',
672 'hash': '',
673 },
674 )
675 best = None
676 best_score = 0.0
677 for hit in (data or {}).get('candidates') or []:
678 if not isinstance(hit, dict) or not hit.get('id'):
679 continue
680 candidate = {
681 'name': hit.get('song'),
682 'artists': [
683 {'name': part}
684 for part in re.split(r'[、,&/]', str(hit.get('singer') or ''))
685 if part.strip()
686 ],
687 'duration': hit.get('duration'),
688 }
689 score = _netease_score(candidate, title, artist, duration)
690 if score > best_score:
691 best, best_score = hit, score
692 if best is None:
693 return None
694 payload = _kugou_get(
695 '/download',
696 {
697 'ver': 1,
698 'client': 'pc',
699 'id': best['id'],
700 'accesskey': best.get('accesskey') or '',
701 'fmt': 'lrc',
702 'charset': 'utf8',
703 },
704 )
705 try:
706 text = base64.b64decode(str((payload or {}).get('content') or ''))
707 lrc = text.decode('utf-8', errors='replace')
708 except (binascii.Error, ValueError):
709 return None
710 # Kugou opens with the song's own "Title - Artist" line.
711 heading = {
712 _normalize(f'{best.get("song")} - {best.get("singer")}'),
713 _normalize(f'{best.get("singer")} - {best.get("song")}'),
714 }
715 lines = [
716 line
717 for line in lrc.splitlines()
718 if not _LRC_TAG.match(line.strip())
719 and _normalize(_LRC_LINE.sub(r'\2', line.strip())) not in heading
720 ]
721 result = _parse_lrc('\n'.join(lines))
722 return result if result.has_any() else None
725_PROVIDER_FNS: dict[str, Callable[[dict[str, Any]], Optional[Lyrics]]] = {
726 'lrclib': _fetch_lrclib,
727 'netease': _fetch_netease,
728 'kugou': _fetch_kugou,
729}
732#: Tag keys the downloader embeds plain lyrics under, per container:
733#: ID3 ``USLT`` frames (MP3), MP4 ``©lyr`` and Vorbis-comment ``lyrics``
734#: (FLAC, Ogg Vorbis, Opus). See ``downloader.embed_lyrics``.
735_MP4_LYRICS_KEY = '\xa9lyr'
736_VORBIS_LYRICS_KEY = 'lyrics'
739def _file_tags(path: Path) -> Any:
740 try:
741 audio = MutagenFile(str(path))
742 except Exception:
743 audio = None
744 tags = getattr(audio, 'tags', None)
745 if tags or path.suffix.lower() != '.mp3':
746 return tags
747 # MP3s mutagen can't identify as audio still carry an ID3 header.
748 try:
749 return ID3(str(path))
750 except Exception:
751 return None
754def _embedded_lyrics(path: Path) -> str:
755 try:
756 tags = _file_tags(path)
757 if not tags:
758 return ''
759 if hasattr(tags, 'getall'):
760 frames = tags.getall('USLT')
761 return str(frames[0].text).strip() if frames else ''
762 # Vorbis comments reject MP4's non-ASCII key with ValueError.
763 # Use the tag container, not the filename, to choose a valid key.
764 key = (
765 _MP4_LYRICS_KEY
766 if isinstance(tags, MP4Tags)
767 else _VORBIS_LYRICS_KEY
768 )
769 value = tags.get(key)
770 if value:
771 first = value[0] if isinstance(value, list) else value
772 return str(first).strip()
773 except Exception:
774 # Damaged/unsupported tags must not fail the API or upgrade scan,
775 # or prevent read_track_lyrics from returning a valid sidecar.
776 logger.opt(exception=True).debug(
777 'Could not read embedded lyrics from {}', path
778 )
779 return ''
782def _sylt_lrc(frame: Any) -> str:
783 """An ID3 ``SYLT`` frame as LRC text; empty when its times aren't in
784 milliseconds (format 2) or it holds no lines."""
786 if not isinstance(frame, SYLT) or frame.format != 2:
787 return ''
788 entries = [(str(text).strip(), int(time)) for text, time in frame.text]
789 if not any(text for text, _time in entries):
790 return ''
791 lines = []
792 for text, time in entries:
793 ms = max(0, time)
794 minutes, seconds = ms // 60000, ms // 1000 % 60
795 lines.append(
796 f'[{minutes:02d}:{seconds:02d}.{ms % 1000 // 10:02d}]{text}'
797 )
798 return '\n'.join(lines)
801def embedded_synced_text(path: Path, embedded: Optional[str] = None) -> str:
802 """Time-synced lyrics in the file's own tags, as LRC text: lyrics
803 text with LRC timestamps (as files shared over Soulseek or tagged by
804 other apps often carry), or an ID3 ``SYLT`` frame. Empty when the
805 tags have none, or only plain lyrics. *embedded* is the tag's lyrics
806 text when already read."""
808 if embedded is None:
809 embedded = _embedded_lyrics(path)
810 if looks_like_lrc(embedded):
811 return embedded
812 try:
813 tags = _file_tags(path)
814 if tags and hasattr(tags, 'getall'):
815 for frame in tags.getall('SYLT'):
816 text = _sylt_lrc(frame)
817 if text:
818 return text
819 except Exception:
820 logger.opt(exception=True).debug(
821 'Could not read synced lyrics from {}', path
822 )
823 return ''
826def has_synced_lyrics(path: Path) -> bool:
827 """Whether a track already has time-synced lyrics: a ``.lrc`` sidecar
828 (beside it or in the lyrics folder) or synced lyrics in its tags."""
830 if any(_read_lrc_text(sidecar) for sidecar in lrc_candidates(path)):
831 return True
832 return bool(embedded_synced_text(path))
835def read_track_lyrics(path: Path, *, raw: bool = False) -> dict[str, str]:
836 """Lyrics saved with a downloaded track.
838 ``synced`` is the LRC text of the ``.lrc`` sidecar or, without one,
839 the time-synced lyrics in the file's tags; ``plain`` is the text
840 embedded in the file's tags, timestamps removed. Either can be empty.
841 Unreadable files count as having no lyrics.
843 With *raw*, ``synced`` is the sidecar only and ``plain`` the tag's
844 text exactly as stored.
845 """
847 synced = ''
848 for sidecar in lrc_candidates(path):
849 synced = _read_lrc_text(sidecar)
850 if synced:
851 break
852 plain = _embedded_lyrics(path)
853 if raw:
854 return {'synced': synced, 'plain': plain}
855 if not synced:
856 synced = embedded_synced_text(path, plain)
857 if looks_like_lrc(plain):
858 plain = _strip_lrc_timestamps(plain) or plain
859 return {'synced': synced, 'plain': plain}
862def _read_lrc_text(sidecar: Path) -> str:
863 if not sidecar.is_file():
864 return ''
865 try:
866 return sidecar.read_text(encoding='utf-8').strip()
867 except (OSError, UnicodeDecodeError):
868 logger.opt(exception=True).warning(
869 'Could not read LRC sidecar {}', sidecar
870 )
871 return ''
874def _strip_lrc_timestamps(synced: str) -> str:
875 cleaned = re.sub(r'\[\d{1,2}:\d{2}(?:\.\d{1,3})?\]', '', synced)
876 # Header tags (``[ti:Title]``, ``[offset:0]``) aren't lyrics either.
877 return '\n'.join(
878 line.strip()
879 for line in cleaned.splitlines()
880 if line.strip() and not _LRC_TAG.match(line.strip())
881 )
884def write_to_file(
885 path: Path,
886 lyrics: Lyrics,
887 *,
888 sidecar: Optional[Path] = None,
889 embed_synced: bool = False,
890) -> None:
891 """Embed plain lyrics and write a ``.lrc`` sidecar when they are synced.
893 With *embed_synced* (the ``lyrics_synced_only`` setting), the tag gets
894 the time-synced LRC text instead, so players that only read the
895 file's own tags show synced lyrics too.
897 Same write a download uses (see ``downloader.embed_lyrics``).
898 """
900 if not path.exists() or not lyrics.has_any():
901 return
903 if lyrics.synced:
904 dest = lrc_path_for(path, sidecar)
905 try:
906 dest.parent.mkdir(parents=True, exist_ok=True)
907 dest.write_text(lyrics.synced, encoding='utf-8')
908 except OSError:
909 logger.opt(exception=True).warning(
910 'Could not write LRC sidecar {}', dest
911 )
912 else:
913 _unlink_other_lrc(path, dest)
915 if embed_synced and lyrics.synced:
916 text = lyrics.synced
917 else:
918 text = lyrics.plain or _strip_lrc_timestamps(lyrics.synced or '')
919 if not text:
920 return
921 if not can_mutate_audio(path):
922 logger.debug('Skipping lyrics embed in read-only file {}', path)
923 return
925 suffix = path.suffix.lower().lstrip('.')
926 if suffix == 'mp3':
927 audio = None
928 try:
929 audio = MP3(str(path), ID3=ID3)
930 except Exception:
931 audio = None
932 if audio is not None:
933 if audio.tags is None:
934 audio.add_tags()
935 tags = audio.tags
936 else:
937 tags = ID3(str(path))
938 tags.delall('USLT')
939 tags.add(USLT(encoding=3, lang='eng', desc='', text=text))
940 if audio is not None:
941 audio.save(v2_version=4)
942 else:
943 tags.save(v2_version=4)
944 elif suffix in {'m4a', 'mp4', 'aac'}:
945 audio = MP4(str(path))
946 audio['\xa9lyr'] = text
947 audio.save()
948 elif suffix == 'flac':
949 audio = FLAC(str(path))
950 audio['lyrics'] = text
951 audio.save()
952 elif suffix in {'ogg', 'oga'}:
953 audio = OggVorbis(str(path))
954 audio['lyrics'] = text
955 audio.save()
956 elif suffix == 'opus':
957 audio = OggOpus(str(path))
958 audio['lyrics'] = text
959 audio.save()