From 4f8d77becf716143c70644416f0f6ee2c9b9de5b Mon Sep 17 00:00:00 2001 From: Aran <96021763+Aran404@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:22:21 -0500 Subject: [PATCH 1/5] feat: sync local music lyrics from LRCLIB --- docs/lyrics-sync.md | 24 +++ pyproject.toml | 1 + spotapi/_lyrics_sync.py | 304 ++++++++++++++++++++++++++++++++++++++ spotapi/cli.py | 14 +- tests/test_lyrics_sync.py | 193 ++++++++++++++++++++++++ 5 files changed, 535 insertions(+), 1 deletion(-) create mode 100644 docs/lyrics-sync.md create mode 100644 spotapi/_lyrics_sync.py create mode 100644 tests/test_lyrics_sync.py diff --git a/docs/lyrics-sync.md b/docs/lyrics-sync.md new file mode 100644 index 0000000..daf4f75 --- /dev/null +++ b/docs/lyrics-sync.md @@ -0,0 +1,24 @@ +# Sync lyrics for local music + +Install the optional media dependency: + +```bash +pip install "spotapi[media]" +``` + +Point SpotAPI at a local MP3 or FLAC file, or a directory: + +```bash +spotapi lyrics-sync ./Music +spotapi lyrics-sync ./Music --dry-run +spotapi lyrics-sync ./Music --output ./Lyrics +spotapi lyrics-sync ./Music --embed +``` + +The command queries [LRCLIB](https://lrclib.net/) using the title, artist, album (when present), and duration from your audio tags. It does not upload audio, require a Spotify account, or use Spotify's lyrics service. Only use lyrics you have permission to store. + +Synced lyrics use `.lrc`; unsynced lyrics use `.txt`. Files are saved beside each track unless `--output` is specified, in which case the original relative directory structure is preserved. Existing lyrics are compared before changes; different lyrics require interactive approval. Redirected or noninteractive runs leave existing lyrics unchanged. A synced version never gets replaced by plain text. When upgrading a `.txt` file, its existing contents are retained. + +`--embed` writes FLAC lyrics and unsynced MP3 lyrics; synced MP3 lyrics are saved as `.lrc` sidecars instead. The audio is staged before replacing the original. The command skips ambiguous filenames and invalid metadata, does not reorganize your music library, and stops when the provider is unavailable or rate limited. + +The original `spotapi lyrics` command continues to read entitled Spotify lyrics for a Spotify track. diff --git a/pyproject.toml b/pyproject.toml index 60a6427..a6f408a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -63,6 +63,7 @@ dev = [ "ruff>=0.4", "pytest>=8.0", "pytest-asyncio>=0.24", + "mutagen>=1.47,<2", "playwright>=1.55,<2", ] diff --git a/spotapi/_lyrics_sync.py b/spotapi/_lyrics_sync.py new file mode 100644 index 0000000..fc58216 --- /dev/null +++ b/spotapi/_lyrics_sync.py @@ -0,0 +1,304 @@ +"""Match local music against LRCLIB and save lyrics without silent overwrites.""" + +from __future__ import annotations + +import importlib +import json +import math +import os +import re +import shutil +import sys +import tempfile +import unicodedata +from collections import Counter +from dataclasses import dataclass +from difflib import unified_diff +from importlib.metadata import version +from pathlib import Path +from typing import Any, cast +from urllib.error import HTTPError, URLError +from urllib.parse import urlencode +from urllib.request import Request, urlopen + +_SUFFIXES = {".flac", ".mp3"} +_TIMESTAMP = re.compile(r"(?m)^\[\d+:[0-5]\d(?:\.\d+)?\]") + + +@dataclass(frozen=True, slots=True) +class Track: + path: Path + title: str + artist: str + album: str + duration: float + embedded: tuple[str, ...] = () + timed: bool = False + + +@dataclass(frozen=True, slots=True) +class Lyrics: + text: str + synced: bool + + @property + def suffix(self) -> str: + return ".lrc" if self.synced else ".txt" + + +def _read_track(path: Path) -> Track: + mutagen: Any = importlib.import_module("mutagen") + try: + audio: Any = mutagen.File(path, easy=True) + raw: Any = mutagen.File(path) + if audio is None or raw is None: + raise ValueError("unsupported audio file") + title = str(audio.get("title", [""])[0]).strip() + artist = str(audio.get("artist", [""])[0]).strip() + album = str(audio.get("album", [""])[0]).strip() + duration = float(audio.info.length) + if not title or not artist or not math.isfinite(duration) or duration <= 0: + raise ValueError("missing title, artist or duration") + + if path.suffix.lower() == ".flac": + embedded = tuple(str(value) for value in raw.get("lyrics", [])) + timed = any(_TIMESTAMP.search(value) for value in embedded) + elif raw.tags is not None: + embedded = tuple(str(frame.text) for frame in raw.tags.getall("USLT")) + timed = bool(raw.tags.getall("SYLT")) + else: + embedded, timed = (), False + + return Track(path, title, artist, album, duration, embedded, timed) + except mutagen.MutagenError as error: + raise ValueError(f"cannot read audio metadata: {error}") from error + + +def _normalized(value: str) -> str: + return " ".join(unicodedata.normalize("NFKC", value).casefold().split()) + + +def _match(record: dict[str, object], track: Track) -> Lyrics | None: + if record.get("instrumental") is True: + return None + duration = record.get("duration") + if not isinstance(duration, (int, float)) or not math.isfinite(duration): + return None + if abs(duration - track.duration) > 2: + return None + for key, expected in ( + ("trackName", track.title), + ("artistName", track.artist), + ("albumName", track.album), + ): + actual = record.get(key) + if expected and ( + not isinstance(actual, str) or _normalized(actual) != _normalized(expected) + ): + return None + + synced = record.get("syncedLyrics") + if isinstance(synced, str) and _TIMESTAMP.search(synced): + return Lyrics(synced.strip() + "\n", True) + plain = record.get("plainLyrics") + if isinstance(plain, str) and plain.strip(): + return Lyrics(plain.strip() + "\n", False) + return None + + +def _lookup(track: Track) -> Lyrics | None: + query = urlencode( + { + "track_name": track.title, + "artist_name": track.artist, + "album_name": track.album, + "duration": round(track.duration), + } + ) + request = Request( + f"https://lrclib.net/api/get?{query}", + headers={"User-Agent": f"SpotAPI/{version('spotapi')} (https://github.com/Aran404/SpotAPI)"}, + ) + try: + with urlopen(request, timeout=20) as response: + body = response.read(1_000_001) + except HTTPError as error: + if error.code == 404: + return None + if error.code == 429: + raise RuntimeError("LRCLIB rate limit reached; try again later") from error + raise RuntimeError(f"LRCLIB returned HTTP {error.code}") from error + except URLError as error: + raise RuntimeError(f"LRCLIB is unavailable: {error.reason}") from error + + if len(body) > 1_000_000: + raise ValueError("LRCLIB response exceeds 1 MB") + record: object = json.loads(body) + if not isinstance(record, dict): + raise ValueError("LRCLIB returned an invalid record") + return _match(cast("dict[str, object]", record), track) + + +def _read_text(path: Path) -> str | None: + if path.is_symlink(): + raise ValueError(f"refusing symbolic link: {path}") + return path.read_text(encoding="utf-8-sig") if path.exists() else None + + +def _write_text(path: Path, text: str, previous: str | None) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix=".spotapi-", dir=path.parent) as directory: + staged = Path(directory) / "lyrics" + staged.write_text(text, encoding="utf-8", newline="\n") + if _read_text(path) != previous: + raise ValueError("lyrics changed since review") + if previous is None: + if os.name == "nt": + staged.rename(path) + else: + os.link(staged, path) + else: + shutil.copymode(path, staged) + staged.replace(path) + + +def _embed(path: Path, lyrics: Lyrics) -> None: + mutagen: Any = importlib.import_module("mutagen") + original = path.stat() + with tempfile.TemporaryDirectory(prefix=".spotapi-", dir=path.parent) as directory: + staged = Path(directory) / path.name + shutil.copy2(path, staged) + try: + audio: Any = mutagen.File(staged) + if audio is None: + raise ValueError("unsupported audio file") + if path.suffix.lower() == ".flac": + audio["lyrics"] = [lyrics.text.rstrip("\n")] + else: + id3: Any = importlib.import_module("mutagen.id3") + if audio.tags is None: + audio.add_tags() + audio.tags.delall("USLT") + audio.tags.add(id3.USLT(encoding=3, lang="und", desc="", text=lyrics.text)) + audio.save() + except mutagen.MutagenError as error: + raise ValueError(f"cannot embed lyrics: {error}") from error + current = path.stat() + if path.is_symlink() or (current.st_ino, current.st_size, current.st_mtime_ns) != ( + original.st_ino, + original.st_size, + original.st_mtime_ns, + ): + raise ValueError("audio changed since review") + staged.replace(path) + + +def _visible(text: str) -> str: + return "".join(char if char.isprintable() or char == "\n" else repr(char)[1:-1] for char in text) + + +def _review(previous: str, lyrics: Lyrics, *, dry_run: bool) -> bool: + print( + _visible( + "\n".join( + unified_diff( + previous.splitlines(), + lyrics.text.splitlines(), + fromfile="existing", + tofile="LRCLIB", + lineterm="", + ) + ) + ) + ) + if dry_run: + return True + if not sys.stdin.isatty() or not sys.stdout.isatty(): + return False + try: + return input(" Apply this change? [y/N] ").strip().lower() in {"y", "yes"} + except EOFError: + return False + + +def _save( + track: Track, lyrics: Lyrics, destination: Path, *, embed: bool, dry_run: bool +) -> str: + # MP3 synchronized lyrics remain LRC sidecars; USLT is not a timed tag. + embed = embed and (track.path.suffix.lower() == ".flac" or not lyrics.synced) + lrc = _read_text(destination.with_suffix(".lrc")) + plain = _read_text(destination.with_suffix(".txt")) + if not lyrics.synced and (lrc is not None or track.timed): + return "Kept synced" + if embed and (len(track.embedded) > 1 or (track.timed and not track.embedded)): + return "Kept embedded" + + target = destination.with_suffix(lyrics.suffix) + existing = lrc if lyrics.synced else plain + if embed: + previous = track.embedded[0] if track.embedded else None + else: + previous = existing + if previous is None: + previous = plain if lyrics.synced else None + if previous is None and track.embedded: + previous = "\n".join(track.embedded) + + if previous is not None: + if previous.strip() == lyrics.text.strip(): + return "Unchanged" + if not _review(previous, lyrics, dry_run=dry_run): + return "Kept existing" + if dry_run: + return "Would embed" if embed else f"Would save {lyrics.suffix}" + if embed: + _embed(track.path, lyrics) + return "Embedded" + _write_text(target, lyrics.text, existing) + return f"Saved {lyrics.suffix}" + + +def run(path: Path, *, output: Path | None, embed: bool, dry_run: bool) -> int: + """Process a file or directory, preserving existing lyrics by default.""" + if importlib.util.find_spec("mutagen") is None: + raise RuntimeError('Install lyrics sync with: pip install "spotapi[media]"') + if not path.exists() or path.is_symlink(): + raise ValueError(f"not a local audio file or directory: {path}") + root = path if path.is_dir() else path.parent + files = sorted( + file + for file in (path.rglob("*") if path.is_dir() else (path,)) + if file.is_file() and not file.is_symlink() and file.suffix.lower() in _SUFFIXES + ) + if not files: + raise ValueError("no MP3 or FLAC files found") + + destinations = [output / file.relative_to(root) if output else file for file in files] + stems = Counter(str(file.with_suffix("")).casefold() for file in destinations) + counts: Counter[str] = Counter() + print(f"LRCLIB | {len(files)} track{'s' if len(files) != 1 else ''}") + if dry_run: + print("Dry run: no files will be changed.") + print() + + for file, destination in zip(files, destinations, strict=True): + label = _visible(str(file.relative_to(root))) + try: + if stems[str(destination.with_suffix("")).casefold()] > 1: + raise ValueError("multiple audio files share this lyrics filename") + if not destination.parent.resolve().is_relative_to((output or root).resolve()): + raise ValueError("output path escapes the destination directory") + track = _read_track(file) + lyrics = _lookup(track) + if lyrics is None: + status = "Not found" + else: + status = _save(track, lyrics, destination, embed=embed, dry_run=dry_run) + except (OSError, ValueError) as error: + status = "Skipped" + label += f" ({_visible(str(error))})" + counts[status] += 1 + print(f" {status:<16} {label}") + + print("\n" + " | ".join(f"{count} {status.lower()}" for status, count in counts.items())) + return int(counts["Skipped"] > 0) diff --git a/spotapi/cli.py b/spotapi/cli.py index 6fa6ab9..6a41f14 100644 --- a/spotapi/cli.py +++ b/spotapi/cli.py @@ -13,6 +13,7 @@ from collections.abc import AsyncGenerator, Awaitable, Callable, Sequence from contextlib import aclosing, asynccontextmanager from importlib.metadata import version as package_version +from pathlib import Path from typing import NoReturn, cast from .account import Private @@ -46,6 +47,7 @@ ("get", "Look up a Spotify URL or URI"), ("credits", "Track credits"), ("lyrics", "Lyrics (account required)"), + ("lyrics-sync", "Find lyrics for local music"), ("transcript", "Episode transcripts"), ), ), @@ -142,7 +144,7 @@ def _add_output_options(parser: argparse.ArgumentParser) -> None: for child in children.values(): _add_output_options(child) return - if parser.prog.split()[-1] in {"studio", "discover", "connect"}: + if parser.prog.split()[-1] in {"studio", "discover", "connect", "lyrics-sync"}: return if not any("--json" in action.option_strings for action in parser._actions): parser.add_argument("--json", action="store_true", help="output raw JSON for scripts") @@ -282,6 +284,12 @@ def _parser() -> argparse.ArgumentParser: ("lyrics", "read entitled lyrics using SPOTIFY_COOKIE"), ): commands.add_parser(name, help=help_text).add_argument("resource") + sync = commands.add_parser("lyrics-sync", help="find lyrics for local MP3 and FLAC files") + sync.add_argument("path", type=Path, help="audio file or directory") + storage = sync.add_mutually_exclusive_group() + storage.add_argument("--embed", action="store_true", help="embed lyrics where supported") + storage.add_argument("--output", type=Path, help="save sidecars in a separate directory") + sync.add_argument("--dry-run", action="store_true", help="preview without changing files") commands.add_parser("charts", help="list editorial chart shortcuts") _configure_download( commands.add_parser("download", help="save published preview, cover or Canvas assets") @@ -610,6 +618,10 @@ def main(argv: Sequence[str] | None = None) -> int: profile_name(args.profile) controller = importlib.import_module("spotapi._connect.app") asyncio.run(controller.run_connect(args.profile, force=args.force)) + case "lyrics-sync": + from ._lyrics_sync import run + + return run(args.path, output=args.output, embed=args.embed, dry_run=args.dry_run) case "discover": dependencies = ("textual", "textual_image", "PIL", "httpx") if any(importlib.util.find_spec(name) is None for name in dependencies): diff --git a/tests/test_lyrics_sync.py b/tests/test_lyrics_sync.py new file mode 100644 index 0000000..943805e --- /dev/null +++ b/tests/test_lyrics_sync.py @@ -0,0 +1,193 @@ +"""Local lyrics matching, review and file safety.""" + +from __future__ import annotations + +import base64 +import importlib +import io +import json +from pathlib import Path +from typing import Any +from urllib.error import HTTPError, URLError + +import pytest + +from spotapi import _lyrics_sync as sync +from spotapi.cli import _parser, main + +# A short, silent FLAC recording; no copyrighted audio or lyrics are used. +_FLAC = ( + "ZkxhQwAAACICQAJAAAALAAAMAfQA8AAAAyBq0A9H2K1PEgBbIrLKpI94hAAADgYAAABmZm1wZWc" + "AAAAA//gkCADKAAAAznb/+GQIAd/lAAAAzwo=" +) + + +@pytest.fixture +def track(tmp_path: Path) -> sync.Track: + path = tmp_path / "été.flac" + path.write_bytes(base64.b64decode(_FLAC)) + flac: Any = importlib.import_module("mutagen.flac") + audio: Any = flac.FLAC(path) + audio["title"] = "Summer" + audio["artist"] = "Example" + audio["album"] = "Demo" + audio.save() + return sync._read_track(path) + + +def _record(track: sync.Track, **changes: object) -> dict[str, object]: + return { + "trackName": track.title, + "artistName": track.artist, + "albumName": track.album, + "duration": track.duration, + "plainLyrics": "hello", + "syncedLyrics": "[00:00.00] hello", + **changes, + } + + +def test_read_and_match(track: sync.Track) -> None: + assert (track.title, track.artist, track.album) == ("Summer", "Example", "Demo") + assert not track.embedded + assert sync._match(_record(track), track) == sync.Lyrics("[00:00.00] hello\n", True) + assert sync._match(_record(track, syncedLyrics=None), track) == sync.Lyrics("hello\n", False) + assert sync._match(_record(track, trackName=" SUMMER "), track) is not None + + +@pytest.mark.parametrize( + "changes", + [ + {"instrumental": True}, + {"duration": None}, + {"duration": 50}, + {"trackName": "Different"}, + {"artistName": "Different"}, + {"albumName": "Different"}, + {"plainLyrics": "", "syncedLyrics": "invalid"}, + ], +) +def test_reject_mismatch(track: sync.Track, changes: dict[str, object]) -> None: + assert sync._match(_record(track, **changes), track) is None + + +def test_lookup(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sync, "urlopen", lambda *a, **kw: io.BytesIO(json.dumps(_record(track)).encode())) + assert sync._lookup(track) == sync.Lyrics("[00:00.00] hello\n", True) + + +@pytest.mark.parametrize("code", [404, 429, 503]) +def test_http_status(track: sync.Track, monkeypatch: pytest.MonkeyPatch, code: int) -> None: + def fail(*args: object, **kwargs: object) -> Any: + raise HTTPError("https://lrclib.net", code, "error", {}, None) + + monkeypatch.setattr(sync, "urlopen", fail) + if code == 404: + assert sync._lookup(track) is None + else: + with pytest.raises(RuntimeError, match="LRCLIB"): + sync._lookup(track) + + +def test_network_failure(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: + def fail(*args: object, **kwargs: object) -> Any: + raise URLError("offline") + + monkeypatch.setattr(sync, "urlopen", fail) + with pytest.raises(RuntimeError, match="unavailable"): + sync._lookup(track) + + +@pytest.mark.parametrize("body", [b"[]", b"x" * 1_000_001, b"invalid json"]) +def test_invalid_response(track: sync.Track, monkeypatch: pytest.MonkeyPatch, body: bytes) -> None: + monkeypatch.setattr(sync, "urlopen", lambda *a, **kw: io.BytesIO(body)) + with pytest.raises(ValueError): + sync._lookup(track) + + +def test_sidecar_lifecycle(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: + path = track.path + plain = sync.Lyrics("old\n", False) + timed = sync.Lyrics("[00:00.00] new\n", True) + assert sync._save(track, plain, path, embed=False, dry_run=True) == "Would save .txt" + assert not path.with_suffix(".txt").exists() + assert sync._save(track, plain, path, embed=False, dry_run=False) == "Saved .txt" + assert sync._save(track, plain, path, embed=False, dry_run=False) == "Unchanged" + monkeypatch.setattr(sync, "_review", lambda *a, **kw: False) + assert sync._save(track, timed, path, embed=False, dry_run=False) == "Kept existing" + monkeypatch.setattr(sync, "_review", lambda *a, **kw: True) + assert sync._save(track, timed, path, embed=False, dry_run=False) == "Saved .lrc" + assert path.with_suffix(".txt").read_text() == plain.text + assert path.with_suffix(".lrc").read_text() == timed.text + assert sync._save(track, plain, path, embed=False, dry_run=False) == "Kept synced" + + +def test_atomic_replace(tmp_path: Path) -> None: + path = tmp_path / "lyrics.txt" + sync._write_text(path, "old\n", None) + with pytest.raises(ValueError, match="changed"): + sync._write_text(path, "new\n", None) + assert path.read_text() == "old\n" + sync._write_text(path, "new\n", "old\n") + assert path.read_text() == "new\n" + + +def test_embed_flac(track: sync.Track) -> None: + lyrics = sync.Lyrics("[00:00.00] hello\n", True) + assert sync._save(track, lyrics, track.path, embed=True, dry_run=True) == "Would embed" + assert not sync._read_track(track.path).embedded + assert sync._save(track, lyrics, track.path, embed=True, dry_run=False) == "Embedded" + loaded = sync._read_track(track.path) + assert loaded.embedded == (lyrics.text.strip(),) + assert loaded.timed + assert loaded.title == track.title + assert loaded.duration == track.duration + assert sync._save(loaded, lyrics, track.path, embed=True, dry_run=False) == "Unchanged" + + +def test_review(capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch) -> None: + lyrics = sync.Lyrics("new\n", False) + assert sync._review("old", lyrics, dry_run=True) + output = capsys.readouterr().out + assert "-old" in output and "+new" in output + monkeypatch.setattr(sync.sys.stdin, "isatty", lambda: False) + assert not sync._review("old", lyrics, dry_run=False) + monkeypatch.setattr(sync.sys.stdin, "isatty", lambda: True) + monkeypatch.setattr(sync.sys.stdout, "isatty", lambda: True) + monkeypatch.setattr("builtins.input", lambda _: "yes") + assert sync._review("old", lyrics, dry_run=False) + monkeypatch.setattr("builtins.input", lambda _: "") + assert not sync._review("old", lyrics, dry_run=False) + + +def test_cli(track: sync.Track, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: + monkeypatch.setattr(sync, "_lookup", lambda _: sync.Lyrics("hello\n", False)) + output = tmp_path / "Lyrics" + assert main(["lyrics-sync", str(track.path), "--output", str(output), "--dry-run"]) == 0 + assert not output.exists() + assert main(["lyrics-sync", str(track.path), "--output", str(output)]) == 0 + assert (output / "été.txt").read_text(encoding="utf-8") == "hello\n" + assert "Saved .txt" in capsys.readouterr().out + assert _parser().parse_args(["lyrics", "abc"]).resource == "abc" + with pytest.raises(SystemExit): + _parser().parse_args(["lyrics-sync", str(track.path), "--output", str(output), "--embed"]) + + +def test_recursive_and_collision(track: sync.Track, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sync, "_lookup", lambda _: sync.Lyrics("hello\n", False)) + album = tmp_path / "album" + album.mkdir() + moved = album / track.path.name + track.path.rename(moved) + output = tmp_path / "lyrics" + assert sync.run(tmp_path, output=output, embed=False, dry_run=False) == 0 + assert (output / "album" / "été.txt").exists() + moved.with_suffix(".mp3").touch() + assert sync.run(tmp_path, output=output, embed=False, dry_run=False) == 1 + + +def test_missing_tracks(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="no MP3"): + sync.run(tmp_path, output=None, embed=False, dry_run=False) + with pytest.raises(ValueError, match="not a local"): + sync.run(tmp_path / "missing", output=None, embed=False, dry_run=False) From e9ba2cb47450b4a8347e9ee40075d35f2ac14fdc Mon Sep 17 00:00:00 2001 From: Aran <96021763+Aran404@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:23:08 -0500 Subject: [PATCH 2/5] test: exercise lyrics sync against local audio fixtures --- mkdocs.yml | 1 + spotapi/_lyrics_sync.py | 41 ++++++++------ tests/test_lyrics_sync.py | 113 ++++++++++++++++++++++++++++++++++++-- 3 files changed, 134 insertions(+), 21 deletions(-) diff --git a/mkdocs.yml b/mkdocs.yml index 6e484c1..ac1d7e2 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -37,6 +37,7 @@ nav: - Accounts and playlists: account.md - Player controls and events: player.md - Studio: studio.md + - Local lyrics: lyrics-sync.md - Reference: - Python API: reference.md - Request and retry policy: transport.md diff --git a/spotapi/_lyrics_sync.py b/spotapi/_lyrics_sync.py index fc58216..f272851 100644 --- a/spotapi/_lyrics_sync.py +++ b/spotapi/_lyrics_sync.py @@ -3,6 +3,7 @@ from __future__ import annotations import importlib +import importlib.util import json import math import os @@ -53,9 +54,9 @@ def _read_track(path: Path) -> Track: raw: Any = mutagen.File(path) if audio is None or raw is None: raise ValueError("unsupported audio file") - title = str(audio.get("title", [""])[0]).strip() - artist = str(audio.get("artist", [""])[0]).strip() - album = str(audio.get("album", [""])[0]).strip() + title = str((audio.get("title") or [""])[0]).strip() + artist = str((audio.get("artist") or [""])[0]).strip() + album = str((audio.get("album") or [""])[0]).strip() duration = float(audio.info.length) if not title or not artist or not math.isfinite(duration) or duration <= 0: raise ValueError("missing title, artist or duration") @@ -82,7 +83,9 @@ def _match(record: dict[str, object], track: Track) -> Lyrics | None: if record.get("instrumental") is True: return None duration = record.get("duration") - if not isinstance(duration, (int, float)) or not math.isfinite(duration): + if isinstance(duration, bool) or not isinstance(duration, (int, float)): + return None + if not math.isfinite(duration): return None if abs(duration - track.duration) > 2: return None @@ -194,7 +197,9 @@ def _embed(path: Path, lyrics: Lyrics) -> None: def _visible(text: str) -> str: - return "".join(char if char.isprintable() or char == "\n" else repr(char)[1:-1] for char in text) + return "".join( + char if char.isprintable() or char == "\n" else repr(char)[1:-1] for char in text + ) def _review(previous: str, lyrics: Lyrics, *, dry_run: bool) -> bool: @@ -221,9 +226,7 @@ def _review(previous: str, lyrics: Lyrics, *, dry_run: bool) -> bool: return False -def _save( - track: Track, lyrics: Lyrics, destination: Path, *, embed: bool, dry_run: bool -) -> str: +def _save(track: Track, lyrics: Lyrics, destination: Path, *, embed: bool, dry_run: bool) -> str: # MP3 synchronized lyrics remain LRC sidecars; USLT is not a timed tag. embed = embed and (track.path.suffix.lower() == ".flac" or not lyrics.synced) lrc = _read_text(destination.with_suffix(".lrc")) @@ -235,8 +238,8 @@ def _save( target = destination.with_suffix(lyrics.suffix) existing = lrc if lyrics.synced else plain - if embed: - previous = track.embedded[0] if track.embedded else None + if embed and track.embedded: + previous = track.embedded[0] else: previous = existing if previous is None: @@ -246,9 +249,12 @@ def _save( if previous is not None: if previous.strip() == lyrics.text.strip(): - return "Unchanged" - if not _review(previous, lyrics, dry_run=dry_run): - return "Kept existing" + if not embed or track.embedded: + return "Unchanged" + else: + print(f" Review: {_visible(str(track.path))}") + if not _review(previous, lyrics, dry_run=dry_run): + return "Kept existing" if dry_run: return "Would embed" if embed else f"Would save {lyrics.suffix}" if embed: @@ -290,10 +296,11 @@ def run(path: Path, *, output: Path | None, embed: bool, dry_run: bool) -> int: raise ValueError("output path escapes the destination directory") track = _read_track(file) lyrics = _lookup(track) - if lyrics is None: - status = "Not found" - else: - status = _save(track, lyrics, destination, embed=embed, dry_run=dry_run) + status = ( + "Not found" + if lyrics is None + else _save(track, lyrics, destination, embed=embed, dry_run=dry_run) + ) except (OSError, ValueError) as error: status = "Skipped" label += f" ({_visible(str(error))})" diff --git a/tests/test_lyrics_sync.py b/tests/test_lyrics_sync.py index 943805e..992c93b 100644 --- a/tests/test_lyrics_sync.py +++ b/tests/test_lyrics_sync.py @@ -6,6 +6,7 @@ import importlib import io import json +from dataclasses import replace from pathlib import Path from typing import Any from urllib.error import HTTPError, URLError @@ -60,6 +61,8 @@ def test_read_and_match(track: sync.Track) -> None: [ {"instrumental": True}, {"duration": None}, + {"duration": True}, + {"duration": float("inf")}, {"duration": 50}, {"trackName": "Different"}, {"artistName": "Different"}, @@ -72,14 +75,16 @@ def test_reject_mismatch(track: sync.Track, changes: dict[str, object]) -> None: def test_lookup(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(sync, "urlopen", lambda *a, **kw: io.BytesIO(json.dumps(_record(track)).encode())) + monkeypatch.setattr( + sync, "urlopen", lambda *a, **kw: io.BytesIO(json.dumps(_record(track)).encode()) + ) assert sync._lookup(track) == sync.Lyrics("[00:00.00] hello\n", True) @pytest.mark.parametrize("code", [404, 429, 503]) def test_http_status(track: sync.Track, monkeypatch: pytest.MonkeyPatch, code: int) -> None: def fail(*args: object, **kwargs: object) -> Any: - raise HTTPError("https://lrclib.net", code, "error", {}, None) + raise HTTPError("https://lrclib.net", code, "error", None, None) monkeypatch.setattr(sync, "urlopen", fail) if code == 404: @@ -160,7 +165,12 @@ def test_review(capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPa assert not sync._review("old", lyrics, dry_run=False) -def test_cli(track: sync.Track, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: +def test_cli( + track: sync.Track, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: monkeypatch.setattr(sync, "_lookup", lambda _: sync.Lyrics("hello\n", False)) output = tmp_path / "Lyrics" assert main(["lyrics-sync", str(track.path), "--output", str(output), "--dry-run"]) == 0 @@ -173,7 +183,9 @@ def test_cli(track: sync.Track, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, _parser().parse_args(["lyrics-sync", str(track.path), "--output", str(output), "--embed"]) -def test_recursive_and_collision(track: sync.Track, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: +def test_recursive_and_collision( + track: sync.Track, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: monkeypatch.setattr(sync, "_lookup", lambda _: sync.Lyrics("hello\n", False)) album = tmp_path / "album" album.mkdir() @@ -191,3 +203,96 @@ def test_missing_tracks(tmp_path: Path) -> None: sync.run(tmp_path, output=None, embed=False, dry_run=False) with pytest.raises(ValueError, match="not a local"): sync.run(tmp_path / "missing", output=None, embed=False, dry_run=False) + + +def test_mp3(tmp_path: Path) -> None: + # Five silent MPEG frames, produced from a short generated silence clip. + data = ( + "//sQxAADwAABpAAAACAAADSAAAAETEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" + "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+xLE" + "KYPAAAGkAAAAIAAANIAAAARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" + "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+xDEU4PAAAG" + "kAAAAIAAANIAAAARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" + "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7EsR9A8AAAaQAA" + "AAgAAA0gAAABFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" + "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7EMSnA8AA" + "AaQAAAAgAAA0gAAABFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" + "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" + ) + path = tmp_path / "silence.mp3" + path.write_bytes(base64.b64decode(data)) + id3: Any = importlib.import_module("mutagen.id3") + tags: Any = id3.ID3() + tags.add(id3.TIT2(encoding=3, text=["Silence"])) + tags.add(id3.TPE1(encoding=3, text=["Example"])) + tags.save(path) + track = sync._read_track(path) + plain = sync.Lyrics("hello\n", False) + assert sync._save(track, plain, path, embed=True, dry_run=False) == "Embedded" + loaded = sync._read_track(path) + assert loaded.embedded == (plain.text,) + assert loaded.title == track.title + assert loaded.duration == track.duration + synced = sync.Lyrics("[00:00.00] hello\n", True) + assert sync._save(loaded, synced, path, embed=True, dry_run=True) == "Would save .lrc" + + +def test_existing_embedded(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: + lyrics = sync.Lyrics("new\n", False) + multiple = replace(track, embedded=("one", "two")) + assert sync._save(multiple, lyrics, track.path, embed=True, dry_run=False) == "Kept embedded" + timed = replace(track, timed=True) + assert sync._save(timed, lyrics, track.path, embed=False, dry_run=False) == "Kept synced" + existing = replace(track, embedded=("old",)) + monkeypatch.setattr(sync, "_review", lambda *a, **kw: False) + assert sync._save(existing, lyrics, track.path, embed=False, dry_run=False) == "Kept existing" + + +def test_not_found( + track: sync.Track, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.setattr(sync, "_lookup", lambda _: None) + assert sync.run(track.path, output=None, embed=False, dry_run=False) == 0 + assert "Not found" in capsys.readouterr().out + assert not track.path.with_suffix(".txt").exists() + + +def test_invalid_audio(tmp_path: Path) -> None: + path = tmp_path / "broken.flac" + path.write_bytes(b"not audio") + with pytest.raises(ValueError): + sync._read_track(path) + assert sync.run(path, output=None, embed=False, dry_run=False) == 1 + + +def test_missing_dependency(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sync.importlib.util, "find_spec", lambda _: None) + with pytest.raises(RuntimeError, match=r"spotapi\[media\]"): + sync.run(track.path, output=None, embed=False, dry_run=False) + + +def test_terminal_controls() -> None: + assert sync._visible("hello\x1b[2J\nworld") == r"hello\x1b[2J" + "\nworld" + + +def test_review_eof(monkeypatch: pytest.MonkeyPatch) -> None: + def eof(_: str) -> str: + raise EOFError + + monkeypatch.setattr(sync.sys.stdin, "isatty", lambda: True) + monkeypatch.setattr(sync.sys.stdout, "isatty", lambda: True) + monkeypatch.setattr("builtins.input", eof) + assert not sync._review("old", sync.Lyrics("new\n", False), dry_run=False) + + +def test_sidecar_symlink(tmp_path: Path) -> None: + original = tmp_path / "original.txt" + original.write_text("old", encoding="utf-8") + alias = tmp_path / "alias.txt" + try: + alias.symlink_to(original) + except OSError: + pytest.skip("symbolic links are unavailable") + with pytest.raises(ValueError, match="symbolic link"): + sync._write_text(alias, "new", None) + assert original.read_text(encoding="utf-8") == "old" From 0a010cc573fbdee5776cf63b8b5bca5dae17f0c1 Mon Sep 17 00:00:00 2001 From: Aran <96021763+Aran404@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:23:58 -0500 Subject: [PATCH 3/5] fix: preserve concurrent metadata edits during lyrics sync --- spotapi/_lyrics_sync.py | 35 +++++++++++++++----------- spotapi/cli.py | 2 +- tests/test_lyrics_sync.py | 52 +++++++++++++++++++++++---------------- 3 files changed, 52 insertions(+), 37 deletions(-) diff --git a/spotapi/_lyrics_sync.py b/spotapi/_lyrics_sync.py index f272851..cd309a6 100644 --- a/spotapi/_lyrics_sync.py +++ b/spotapi/_lyrics_sync.py @@ -35,6 +35,7 @@ class Track: duration: float embedded: tuple[str, ...] = () timed: bool = False + signature: tuple[int, int, int] | None = None @dataclass(frozen=True, slots=True) @@ -47,7 +48,13 @@ def suffix(self) -> str: return ".lrc" if self.synced else ".txt" +def _signature(path: Path) -> tuple[int, int, int]: + stat = path.stat() + return stat.st_ino, stat.st_size, stat.st_mtime_ns + + def _read_track(path: Path) -> Track: + signature = _signature(path) mutagen: Any = importlib.import_module("mutagen") try: audio: Any = mutagen.File(path, easy=True) @@ -70,7 +77,7 @@ def _read_track(path: Path) -> Track: else: embedded, timed = (), False - return Track(path, title, artist, album, duration, embedded, timed) + return Track(path, title, artist, album, duration, embedded, timed, signature) except mutagen.MutagenError as error: raise ValueError(f"cannot read audio metadata: {error}") from error @@ -118,10 +125,8 @@ def _lookup(track: Track) -> Lyrics | None: "duration": round(track.duration), } ) - request = Request( - f"https://lrclib.net/api/get?{query}", - headers={"User-Agent": f"SpotAPI/{version('spotapi')} (https://github.com/Aran404/SpotAPI)"}, - ) + agent = f"SpotAPI/{version('spotapi')} (https://github.com/Aran404/SpotAPI)" + request = Request(f"https://lrclib.net/api/get?{query}", headers={"User-Agent": agent}) try: with urlopen(request, timeout=20) as response: body = response.read(1_000_001) @@ -165,9 +170,12 @@ def _write_text(path: Path, text: str, previous: str | None) -> None: staged.replace(path) -def _embed(path: Path, lyrics: Lyrics) -> None: +def _embed(track: Track, lyrics: Lyrics) -> None: + path = track.path + original = _signature(path) + if path.is_symlink() or original != track.signature: + raise ValueError("audio changed since review") mutagen: Any = importlib.import_module("mutagen") - original = path.stat() with tempfile.TemporaryDirectory(prefix=".spotapi-", dir=path.parent) as directory: staged = Path(directory) / path.name shutil.copy2(path, staged) @@ -186,12 +194,7 @@ def _embed(path: Path, lyrics: Lyrics) -> None: audio.save() except mutagen.MutagenError as error: raise ValueError(f"cannot embed lyrics: {error}") from error - current = path.stat() - if path.is_symlink() or (current.st_ino, current.st_size, current.st_mtime_ns) != ( - original.st_ino, - original.st_size, - original.st_mtime_ns, - ): + if path.is_symlink() or _signature(path) != original: raise ValueError("audio changed since review") staged.replace(path) @@ -233,7 +236,9 @@ def _save(track: Track, lyrics: Lyrics, destination: Path, *, embed: bool, dry_r plain = _read_text(destination.with_suffix(".txt")) if not lyrics.synced and (lrc is not None or track.timed): return "Kept synced" - if embed and (len(track.embedded) > 1 or (track.timed and not track.embedded)): + if embed and len(track.embedded) > 1: + return "Kept embedded" + if track.timed and not track.embedded and lrc is None: return "Kept embedded" target = destination.with_suffix(lyrics.suffix) @@ -258,7 +263,7 @@ def _save(track: Track, lyrics: Lyrics, destination: Path, *, embed: bool, dry_r if dry_run: return "Would embed" if embed else f"Would save {lyrics.suffix}" if embed: - _embed(track.path, lyrics) + _embed(track, lyrics) return "Embedded" _write_text(target, lyrics.text, existing) return f"Saved {lyrics.suffix}" diff --git a/spotapi/cli.py b/spotapi/cli.py index 6a41f14..be2816a 100644 --- a/spotapi/cli.py +++ b/spotapi/cli.py @@ -130,7 +130,7 @@ def format_help(self) -> str: "", "Run 'spotapi --help' for command-specific options.", "Use --json after a command for machine-readable output.", - "Default output remains JSON when redirected or piped.", + "API output remains JSON when redirected or piped.", "", ) ) diff --git a/tests/test_lyrics_sync.py b/tests/test_lyrics_sync.py index 992c93b..b38b152 100644 --- a/tests/test_lyrics_sync.py +++ b/tests/test_lyrics_sync.py @@ -9,6 +9,7 @@ from dataclasses import replace from pathlib import Path from typing import Any +from unittest.mock import Mock from urllib.error import HTTPError, URLError import pytest @@ -76,7 +77,7 @@ def test_reject_mismatch(track: sync.Track, changes: dict[str, object]) -> None: def test_lookup(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( - sync, "urlopen", lambda *a, **kw: io.BytesIO(json.dumps(_record(track)).encode()) + sync, "urlopen", Mock(return_value=io.BytesIO(json.dumps(_record(track)).encode())) ) assert sync._lookup(track) == sync.Lyrics("[00:00.00] hello\n", True) @@ -105,7 +106,7 @@ def fail(*args: object, **kwargs: object) -> Any: @pytest.mark.parametrize("body", [b"[]", b"x" * 1_000_001, b"invalid json"]) def test_invalid_response(track: sync.Track, monkeypatch: pytest.MonkeyPatch, body: bytes) -> None: - monkeypatch.setattr(sync, "urlopen", lambda *a, **kw: io.BytesIO(body)) + monkeypatch.setattr(sync, "urlopen", Mock(return_value=io.BytesIO(body))) with pytest.raises(ValueError): sync._lookup(track) @@ -118,9 +119,9 @@ def test_sidecar_lifecycle(track: sync.Track, monkeypatch: pytest.MonkeyPatch) - assert not path.with_suffix(".txt").exists() assert sync._save(track, plain, path, embed=False, dry_run=False) == "Saved .txt" assert sync._save(track, plain, path, embed=False, dry_run=False) == "Unchanged" - monkeypatch.setattr(sync, "_review", lambda *a, **kw: False) + monkeypatch.setattr(sync, "_review", Mock(return_value=False)) assert sync._save(track, timed, path, embed=False, dry_run=False) == "Kept existing" - monkeypatch.setattr(sync, "_review", lambda *a, **kw: True) + monkeypatch.setattr(sync, "_review", Mock(return_value=True)) assert sync._save(track, timed, path, embed=False, dry_run=False) == "Saved .lrc" assert path.with_suffix(".txt").read_text() == plain.text assert path.with_suffix(".lrc").read_text() == timed.text @@ -159,9 +160,9 @@ def test_review(capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPa assert not sync._review("old", lyrics, dry_run=False) monkeypatch.setattr(sync.sys.stdin, "isatty", lambda: True) monkeypatch.setattr(sync.sys.stdout, "isatty", lambda: True) - monkeypatch.setattr("builtins.input", lambda _: "yes") + monkeypatch.setattr("builtins.input", Mock(return_value="yes")) assert sync._review("old", lyrics, dry_run=False) - monkeypatch.setattr("builtins.input", lambda _: "") + monkeypatch.setattr("builtins.input", Mock(return_value="")) assert not sync._review("old", lyrics, dry_run=False) @@ -171,7 +172,7 @@ def test_cli( monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], ) -> None: - monkeypatch.setattr(sync, "_lookup", lambda _: sync.Lyrics("hello\n", False)) + monkeypatch.setattr(sync, "_lookup", Mock(return_value=sync.Lyrics("hello\n", False))) output = tmp_path / "Lyrics" assert main(["lyrics-sync", str(track.path), "--output", str(output), "--dry-run"]) == 0 assert not output.exists() @@ -186,7 +187,7 @@ def test_cli( def test_recursive_and_collision( track: sync.Track, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - monkeypatch.setattr(sync, "_lookup", lambda _: sync.Lyrics("hello\n", False)) + monkeypatch.setattr(sync, "_lookup", Mock(return_value=sync.Lyrics("hello\n", False))) album = tmp_path / "album" album.mkdir() moved = album / track.path.name @@ -208,16 +209,16 @@ def test_missing_tracks(tmp_path: Path) -> None: def test_mp3(tmp_path: Path) -> None: # Five silent MPEG frames, produced from a short generated silence clip. data = ( - "//sQxAADwAABpAAAACAAADSAAAAETEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" - "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+xLE" - "KYPAAAGkAAAAIAAANIAAAARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" - "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+xDEU4PAAAG" - "kAAAAIAAANIAAAARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" - "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7EsR9A8AAAaQAA" - "AAgAAA0gAAABFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" - "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7EMSnA8AA" - "AaQAAAAgAAA0gAAABFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" - "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" + "//sQxAADwAABpAAAACAAADSAAAAETEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" + "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+xLEKYPAAAGk" + "AAAAIAAANIAAAARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" + "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+xDEU4PAAAGkAAAAIAAANIAA" + "AARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" + "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7EsR9A8AAAaQAAAAgAAA0gAAABFVVVVVVVVVV" + "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" + "VVVVVVVVVVVVVVVVVVVVVVVVVf/7EMSnA8AAAaQAAAAgAAA0gAAABFVVVVVVVVVVVVVVVVVVVVVV" + "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" + "VVVVVVVVVVVV" ) path = tmp_path / "silence.mp3" path.write_bytes(base64.b64decode(data)) @@ -244,14 +245,14 @@ def test_existing_embedded(track: sync.Track, monkeypatch: pytest.MonkeyPatch) - timed = replace(track, timed=True) assert sync._save(timed, lyrics, track.path, embed=False, dry_run=False) == "Kept synced" existing = replace(track, embedded=("old",)) - monkeypatch.setattr(sync, "_review", lambda *a, **kw: False) + monkeypatch.setattr(sync, "_review", Mock(return_value=False)) assert sync._save(existing, lyrics, track.path, embed=False, dry_run=False) == "Kept existing" def test_not_found( track: sync.Track, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: - monkeypatch.setattr(sync, "_lookup", lambda _: None) + monkeypatch.setattr(sync, "_lookup", Mock(return_value=None)) assert sync.run(track.path, output=None, embed=False, dry_run=False) == 0 assert "Not found" in capsys.readouterr().out assert not track.path.with_suffix(".txt").exists() @@ -266,7 +267,7 @@ def test_invalid_audio(tmp_path: Path) -> None: def test_missing_dependency(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(sync.importlib.util, "find_spec", lambda _: None) + monkeypatch.setattr(sync.importlib.util, "find_spec", Mock(return_value=None)) with pytest.raises(RuntimeError, match=r"spotapi\[media\]"): sync.run(track.path, output=None, embed=False, dry_run=False) @@ -296,3 +297,12 @@ def test_sidecar_symlink(tmp_path: Path) -> None: with pytest.raises(ValueError, match="symbolic link"): sync._write_text(alias, "new", None) assert original.read_text(encoding="utf-8") == "old" + + +def test_changed_audio_is_not_replaced(track: sync.Track) -> None: + original = track.path.read_bytes() + changed = original + b"changed" + track.path.write_bytes(changed) + with pytest.raises(ValueError, match="audio changed"): + sync._embed(track, sync.Lyrics("hello\n", False)) + assert track.path.read_bytes() == changed From 7d88fb2b689d37b711457e4ae9279134b99feaa1 Mon Sep 17 00:00:00 2001 From: Aran <96021763+Aran404@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:25:25 -0500 Subject: [PATCH 4/5] fix: narrow tag types and cover failed audio writes --- spotapi/_lyrics_sync.py | 9 +++-- tests/test_lyrics_sync.py | 81 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 85 insertions(+), 5 deletions(-) diff --git a/spotapi/_lyrics_sync.py b/spotapi/_lyrics_sync.py index cd309a6..79bb788 100644 --- a/spotapi/_lyrics_sync.py +++ b/spotapi/_lyrics_sync.py @@ -187,10 +187,11 @@ def _embed(track: Track, lyrics: Lyrics) -> None: audio["lyrics"] = [lyrics.text.rstrip("\n")] else: id3: Any = importlib.import_module("mutagen.id3") - if audio.tags is None: - audio.add_tags() - audio.tags.delall("USLT") - audio.tags.add(id3.USLT(encoding=3, lang="und", desc="", text=lyrics.text)) + tags: Any = audio.tags + if tags is None: + raise ValueError("audio tags disappeared since review") + tags.delall("USLT") + tags.add(id3.USLT(encoding=3, lang="und", desc="", text=lyrics.text)) audio.save() except mutagen.MutagenError as error: raise ValueError(f"cannot embed lyrics: {error}") from error diff --git a/tests/test_lyrics_sync.py b/tests/test_lyrics_sync.py index b38b152..3d8c909 100644 --- a/tests/test_lyrics_sync.py +++ b/tests/test_lyrics_sync.py @@ -7,6 +7,7 @@ import io import json from dataclasses import replace +from email.message import Message from pathlib import Path from typing import Any from unittest.mock import Mock @@ -85,7 +86,7 @@ def test_lookup(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: @pytest.mark.parametrize("code", [404, 429, 503]) def test_http_status(track: sync.Track, monkeypatch: pytest.MonkeyPatch, code: int) -> None: def fail(*args: object, **kwargs: object) -> Any: - raise HTTPError("https://lrclib.net", code, "error", None, None) + raise HTTPError("https://lrclib.net", code, "error", Message(), None) monkeypatch.setattr(sync, "urlopen", fail) if code == 404: @@ -306,3 +307,81 @@ def test_changed_audio_is_not_replaced(track: sync.Track) -> None: with pytest.raises(ValueError, match="audio changed"): sync._embed(track, sync.Lyrics("hello\n", False)) assert track.path.read_bytes() == changed + + +def test_untagged_audio(tmp_path: Path) -> None: + path = tmp_path / "untagged.flac" + path.write_bytes(base64.b64decode(_FLAC)) + with pytest.raises(ValueError, match="missing title"): + sync._read_track(path) + + +def test_unsupported_audio(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: + mutagen: Any = importlib.import_module("mutagen") + monkeypatch.setattr(mutagen, "File", Mock(return_value=None)) + with pytest.raises(ValueError, match="unsupported audio"): + sync._read_track(track.path) + with pytest.raises(ValueError, match="unsupported audio"): + sync._embed(track, sync.Lyrics("hello\n", False)) + + +def test_failed_embed_preserves_audio(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: + mutagen: Any = importlib.import_module("mutagen") + original = track.path.read_bytes() + monkeypatch.setattr(mutagen, "File", Mock(side_effect=mutagen.MutagenError("invalid tags"))) + with pytest.raises(ValueError, match="cannot embed"): + sync._embed(track, sync.Lyrics("hello\n", False)) + assert track.path.read_bytes() == original + assert list(track.path.parent.iterdir()) == [track.path] + + +def test_audio_changes_during_embed(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: + mutagen: Any = importlib.import_module("mutagen") + open_audio: Any = mutagen.File + changed = track.path.read_bytes() + b"concurrent change" + + def modify(path: Path) -> Any: + track.path.write_bytes(changed) + return open_audio(path) + + monkeypatch.setattr(mutagen, "File", modify) + with pytest.raises(ValueError, match="audio changed"): + sync._embed(track, sync.Lyrics("hello\n", False)) + assert track.path.read_bytes() == changed + + +def test_embed_identical_sidecar(track: sync.Track) -> None: + lyrics = sync.Lyrics("hello\n", False) + sidecar = track.path.with_suffix(".txt") + sidecar.write_text(lyrics.text, encoding="utf-8") + assert sync._save(track, lyrics, track.path, embed=True, dry_run=False) == "Embedded" + assert sync._read_track(track.path).embedded == ("hello",) + assert sidecar.read_text(encoding="utf-8") == lyrics.text + + +def test_preserve_existing_timed_tags(track: sync.Track) -> None: + timed = replace(track, timed=True) + lyrics = sync.Lyrics("[00:00.00] hello\n", True) + assert sync._save(timed, lyrics, track.path, embed=False, dry_run=False) == "Kept embedded" + assert not track.path.with_suffix(".lrc").exists() + + +def test_output_symlink_escape( + track: sync.Track, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + album = tmp_path / "album" + album.mkdir() + track.path.rename(album / track.path.name) + output = tmp_path / "output" + output.mkdir() + outside = tmp_path / "outside" + outside.mkdir() + try: + (output / "album").symlink_to(outside, target_is_directory=True) + except OSError: + pytest.skip("symbolic links are unavailable") + lookup = Mock(return_value=sync.Lyrics("hello\n", False)) + monkeypatch.setattr(sync, "_lookup", lookup) + assert sync.run(tmp_path, output=output, embed=False, dry_run=False) == 1 + lookup.assert_not_called() + assert not list(outside.iterdir()) From 07da14c6ffd892bdb77fb7de6363b4c1c396c6da Mon Sep 17 00:00:00 2001 From: Aran <96021763+Aran404@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:26:14 -0500 Subject: [PATCH 5/5] fix: respect LRCLIB batch request limits --- docs/lyrics-sync.md | 2 +- spotapi/_lyrics_sync.py | 33 ++++++++++++++++++-------- tests/test_lyrics_sync.py | 49 ++++++++++++++++++++++++++++++++++++--- 3 files changed, 70 insertions(+), 14 deletions(-) diff --git a/docs/lyrics-sync.md b/docs/lyrics-sync.md index daf4f75..6ddf671 100644 --- a/docs/lyrics-sync.md +++ b/docs/lyrics-sync.md @@ -19,6 +19,6 @@ The command queries [LRCLIB](https://lrclib.net/) using the title, artist, album Synced lyrics use `.lrc`; unsynced lyrics use `.txt`. Files are saved beside each track unless `--output` is specified, in which case the original relative directory structure is preserved. Existing lyrics are compared before changes; different lyrics require interactive approval. Redirected or noninteractive runs leave existing lyrics unchanged. A synced version never gets replaced by plain text. When upgrading a `.txt` file, its existing contents are retained. -`--embed` writes FLAC lyrics and unsynced MP3 lyrics; synced MP3 lyrics are saved as `.lrc` sidecars instead. The audio is staged before replacing the original. The command skips ambiguous filenames and invalid metadata, does not reorganize your music library, and stops when the provider is unavailable or rate limited. +`--embed` writes FLAC lyrics and unsynced MP3 lyrics; synced MP3 lyrics are saved as `.lrc` sidecars instead. The audio is staged before replacing the original. The command skips ambiguous filenames and invalid metadata, does not reorganize your music library, and stops when the provider is unavailable or rate limited. Lookups are intentionally sequential and spaced apart to respect LRCLIB's batch-client guidelines. The original `spotapi lyrics` command continues to read entitled Spotify lyrics for a Spotify track. diff --git a/spotapi/_lyrics_sync.py b/spotapi/_lyrics_sync.py index 79bb788..018b270 100644 --- a/spotapi/_lyrics_sync.py +++ b/spotapi/_lyrics_sync.py @@ -17,6 +17,7 @@ from difflib import unified_diff from importlib.metadata import version from pathlib import Path +from time import sleep from typing import Any, cast from urllib.error import HTTPError, URLError from urllib.parse import urlencode @@ -67,6 +68,8 @@ def _read_track(path: Path) -> Track: duration = float(audio.info.length) if not title or not artist or not math.isfinite(duration) or duration <= 0: raise ValueError("missing title, artist or duration") + if duration > 3600: + raise ValueError("duration exceeds LRCLIB's one-hour limit") if path.suffix.lower() == ".flac": embedded = tuple(str(value) for value in raw.get("lyrics", [])) @@ -117,24 +120,29 @@ def _match(record: dict[str, object], track: Track) -> Lyrics | None: def _lookup(track: Track) -> Lyrics | None: - query = urlencode( - { - "track_name": track.title, - "artist_name": track.artist, - "album_name": track.album, - "duration": round(track.duration), - } - ) + params: dict[str, str | int] = { + "track_name": track.title, + "artist_name": track.artist, + "duration": max(1, round(track.duration)), + } + if track.album: + params["album_name"] = track.album + query = urlencode(params) agent = f"SpotAPI/{version('spotapi')} (https://github.com/Aran404/SpotAPI)" request = Request(f"https://lrclib.net/api/get?{query}", headers={"User-Agent": agent}) try: with urlopen(request, timeout=20) as response: + if response.headers.get_content_type() != "application/json": + raise ValueError("LRCLIB returned a non-JSON response") body = response.read(1_000_001) except HTTPError as error: if error.code == 404: return None - if error.code == 429: - raise RuntimeError("LRCLIB rate limit reached; try again later") from error + if error.code in {429, 503}: + retry = error.headers.get("Retry-After") + reason = "rate limit reached" if error.code == 429 else "temporarily unavailable" + delay = f" (Retry-After: {_visible(retry)})" if retry else "" + raise RuntimeError(f"LRCLIB {reason}; try again later{delay}") from error raise RuntimeError(f"LRCLIB returned HTTP {error.code}") from error except URLError as error: raise RuntimeError(f"LRCLIB is unavailable: {error.reason}") from error @@ -288,6 +296,7 @@ def run(path: Path, *, output: Path | None, embed: bool, dry_run: bool) -> int: destinations = [output / file.relative_to(root) if output else file for file in files] stems = Counter(str(file.with_suffix("")).casefold() for file in destinations) counts: Counter[str] = Counter() + requested = False print(f"LRCLIB | {len(files)} track{'s' if len(files) != 1 else ''}") if dry_run: print("Dry run: no files will be changed.") @@ -301,6 +310,10 @@ def run(path: Path, *, output: Path | None, embed: bool, dry_run: bool) -> int: if not destination.parent.resolve().is_relative_to((output or root).resolve()): raise ValueError("output path escapes the destination directory") track = _read_track(file) + # LRCLIB asks batch clients to space requests and avoid concurrency. + if requested: + sleep(0.75) + requested = True lyrics = _lookup(track) status = ( "Not found" diff --git a/tests/test_lyrics_sync.py b/tests/test_lyrics_sync.py index 3d8c909..076657a 100644 --- a/tests/test_lyrics_sync.py +++ b/tests/test_lyrics_sync.py @@ -25,6 +25,18 @@ ) +class _Response(io.BytesIO): + def __init__(self, body: bytes, content_type: str = "application/json") -> None: + super().__init__(body) + self.headers = Message() + self.headers["Content-Type"] = content_type + + +@pytest.fixture(autouse=True) +def no_network_delay(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sync, "sleep", Mock()) + + @pytest.fixture def track(tmp_path: Path) -> sync.Track: path = tmp_path / "été.flac" @@ -78,7 +90,7 @@ def test_reject_mismatch(track: sync.Track, changes: dict[str, object]) -> None: def test_lookup(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( - sync, "urlopen", Mock(return_value=io.BytesIO(json.dumps(_record(track)).encode())) + sync, "urlopen", Mock(return_value=_Response(json.dumps(_record(track)).encode())) ) assert sync._lookup(track) == sync.Lyrics("[00:00.00] hello\n", True) @@ -86,7 +98,9 @@ def test_lookup(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: @pytest.mark.parametrize("code", [404, 429, 503]) def test_http_status(track: sync.Track, monkeypatch: pytest.MonkeyPatch, code: int) -> None: def fail(*args: object, **kwargs: object) -> Any: - raise HTTPError("https://lrclib.net", code, "error", Message(), None) + headers = Message() + headers["Retry-After"] = "10" + raise HTTPError("https://lrclib.net", code, "error", headers, None) monkeypatch.setattr(sync, "urlopen", fail) if code == 404: @@ -107,7 +121,7 @@ def fail(*args: object, **kwargs: object) -> Any: @pytest.mark.parametrize("body", [b"[]", b"x" * 1_000_001, b"invalid json"]) def test_invalid_response(track: sync.Track, monkeypatch: pytest.MonkeyPatch, body: bytes) -> None: - monkeypatch.setattr(sync, "urlopen", Mock(return_value=io.BytesIO(body))) + monkeypatch.setattr(sync, "urlopen", Mock(return_value=_Response(body))) with pytest.raises(ValueError): sync._lookup(track) @@ -385,3 +399,32 @@ def test_output_symlink_escape( assert sync.run(tmp_path, output=output, embed=False, dry_run=False) == 1 lookup.assert_not_called() assert not list(outside.iterdir()) + + +def test_non_json_response(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sync, "urlopen", Mock(return_value=_Response(b"html", "text/html"))) + with pytest.raises(ValueError, match="non-JSON"): + sync._lookup(track) + + +def test_batch_spacing(track: sync.Track, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + second = tmp_path / "second.flac" + second.write_bytes(track.path.read_bytes()) + lookup = Mock(return_value=sync.Lyrics("hello\n", False)) + delay = Mock() + monkeypatch.setattr(sync, "_lookup", lookup) + monkeypatch.setattr(sync, "sleep", delay) + assert sync.run(tmp_path, output=None, embed=False, dry_run=False) == 0 + assert lookup.call_count == 2 + delay.assert_called_once_with(0.75) + + +def test_lookup_without_album(track: sync.Track, monkeypatch: pytest.MonkeyPatch) -> None: + track = replace(track, album="") + response = _Response(json.dumps(_record(track)).encode()) + lookup = Mock(return_value=response) + monkeypatch.setattr(sync, "urlopen", lookup) + assert sync._lookup(track) is not None + request = lookup.call_args.args[0] + assert "album_name" not in request.full_url + assert "duration=1" in request.full_url