Skip to content

Commit f09f01b

Browse files
committed
Improve flags structure and add tests
1 parent fa42b09 commit f09f01b

File tree

3 files changed

+74
-41
lines changed

3 files changed

+74
-41
lines changed

beetsplug/lyrics.py

+35-38
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242

4343
if TYPE_CHECKING:
4444
from beets.importer import ImportTask
45-
from beets.library import Item
45+
from beets.library import Item, Library
4646

4747
from ._typing import (
4848
GeniusAPI,
@@ -936,7 +936,6 @@ def translator(self) -> Translator | None:
936936

937937
def __init__(self):
938938
super().__init__()
939-
self.import_stages = [self.imported]
940939
self.config.add(
941940
{
942941
"auto": True,
@@ -955,6 +954,7 @@ def __init__(self):
955954
"fallback": None,
956955
"force": False,
957956
"local": False,
957+
"print": False,
958958
"synced": False,
959959
# Musixmatch is disabled by default as they are currently blocking
960960
# requests with the beets user agent.
@@ -968,14 +968,16 @@ def __init__(self):
968968
self.config["google_engine_ID"].redact = True
969969
self.config["genius_api_key"].redact = True
970970

971+
if self.config["auto"]:
972+
self.import_stages = [self.imported]
973+
971974
def commands(self):
972975
cmd = ui.Subcommand("lyrics", help="fetch song lyrics")
973976
cmd.parser.add_option(
974977
"-p",
975978
"--print",
976-
dest="printlyr",
977979
action="store_true",
978-
default=False,
980+
default=self.config["print"].get(),
979981
help="print lyrics to console",
980982
)
981983
cmd.parser.add_option(
@@ -990,34 +992,27 @@ def commands(self):
990992
cmd.parser.add_option(
991993
"-f",
992994
"--force",
993-
dest="force_refetch",
994995
action="store_true",
995-
default=False,
996+
default=self.config["force"].get(),
996997
help="always re-download lyrics",
997998
)
998999
cmd.parser.add_option(
9991000
"-l",
10001001
"--local",
1001-
dest="local_only",
10021002
action="store_true",
1003-
default=False,
1003+
default=self.config["local"].get(),
10041004
help="do not fetch missing lyrics",
10051005
)
10061006

1007-
def func(lib, opts, args):
1007+
def func(lib: Library, opts, args) -> None:
10081008
# The "write to files" option corresponds to the
10091009
# import_write config value.
1010-
items = list(lib.items(ui.decargs(args)))
1010+
self.config.set(vars(opts))
1011+
items = list(lib.items(args))
10111012
for item in items:
1012-
if not opts.local_only and not self.config["local"]:
1013-
self.fetch_item_lyrics(
1014-
item,
1015-
ui.should_write(),
1016-
opts.force_refetch or self.config["force"],
1017-
)
1018-
if item.lyrics:
1019-
if opts.printlyr:
1020-
ui.print_(item.lyrics)
1013+
self.add_item_lyrics(item, ui.should_write())
1014+
if item.lyrics and opts.print:
1015+
ui.print_(item.lyrics)
10211016

10221017
if opts.rest_directory and (
10231018
items := [i for i in items if i.lyrics]
@@ -1029,32 +1024,34 @@ def func(lib, opts, args):
10291024

10301025
def imported(self, _, task: ImportTask) -> None:
10311026
"""Import hook for fetching lyrics automatically."""
1032-
if self.config["auto"]:
1033-
for item in task.imported_items():
1034-
self.fetch_item_lyrics(item, False, self.config["force"])
1027+
for item in task.imported_items():
1028+
self.add_item_lyrics(item, False)
1029+
1030+
def find_lyrics(self, item: Item) -> str:
1031+
album, length = item.album, round(item.length)
1032+
matches = (
1033+
[
1034+
lyrics
1035+
for t in titles
1036+
if (lyrics := self.get_lyrics(a, t, album, length))
1037+
]
1038+
for a, titles in search_pairs(item)
1039+
)
10351040

1036-
def fetch_item_lyrics(self, item: Item, write: bool, force: bool) -> None:
1041+
return "\n\n---\n\n".join(next(filter(None, matches), []))
1042+
1043+
def add_item_lyrics(self, item: Item, write: bool) -> None:
10371044
"""Fetch and store lyrics for a single item. If ``write``, then the
10381045
lyrics will also be written to the file itself.
10391046
"""
1040-
# Skip if the item already has lyrics.
1041-
if not force and item.lyrics:
1042-
self.info("🔵 Lyrics already present: {}", item)
1047+
if self.config["local"]:
10431048
return
10441049

1045-
lyrics_matches = []
1046-
album, length = item.album, round(item.length)
1047-
for artist, titles in search_pairs(item):
1048-
lyrics_matches = [
1049-
self.get_lyrics(artist, title, album, length)
1050-
for title in titles
1051-
]
1052-
if any(lyrics_matches):
1053-
break
1054-
1055-
lyrics = "\n\n---\n\n".join(filter(None, lyrics_matches))
1050+
if not self.config["force"] and item.lyrics:
1051+
self.info("🔵 Lyrics already present: {}", item)
1052+
return
10561053

1057-
if lyrics:
1054+
if lyrics := self.find_lyrics(item):
10581055
self.info("🟢 Found lyrics: {0}", item)
10591056
if translator := self.translator:
10601057
initial_lyrics = lyrics

docs/plugins/lyrics.rst

+2
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ Default configuration:
4747
force: no
4848
google_API_key: null
4949
google_engine_ID: 009217259823014548361:lndtuqkycfu
50+
print: no
5051
sources: [lrclib, google, genius, tekstowo]
5152
synced: no
5253
@@ -74,6 +75,7 @@ The available options are:
7475
- **google_engine_ID**: The custom search engine to use.
7576
Default: The `beets custom search engine`_, which gathers an updated list of
7677
sources known to be scrapeable.
78+
- **print**: Print lyrics to the console.
7779
- **sources**: List of sources to search for lyrics. An asterisk ``*`` expands
7880
to all available sources. The ``google`` source will be automatically
7981
deactivated if no ``google_API_key`` is setup.

test/plugins/test_lyrics.py

+37-3
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
import pytest
2424

2525
from beets.library import Item
26-
from beets.test.helper import PluginMixin
26+
from beets.test.helper import PluginMixin, TestHelper
2727
from beetsplug import lyrics
2828

2929
from .lyrics_pages import LyricsPage, lyrics_pages
@@ -35,6 +35,14 @@
3535
}
3636

3737

38+
@pytest.fixture(scope="module")
39+
def helper():
40+
helper = TestHelper()
41+
helper.setup_beets()
42+
yield helper
43+
helper.teardown_beets()
44+
45+
3846
class TestLyricsUtils:
3947
@pytest.mark.parametrize(
4048
"artist, title",
@@ -232,6 +240,27 @@ def test_error_handling(
232240
assert last_log
233241
assert re.search(expected_log_match, last_log, re.I)
234242

243+
@pytest.mark.parametrize(
244+
"plugin_config, found, expected",
245+
[
246+
({}, "new", "old"),
247+
({"force": True}, "new", "new"),
248+
({"force": True, "local": True}, "new", "old"),
249+
({"force": True, "fallback": None}, "", "old"),
250+
({"force": True, "fallback": ""}, "", ""),
251+
({"force": True, "fallback": "default"}, "", "default"),
252+
],
253+
)
254+
def test_overwrite_config(
255+
self, monkeypatch, helper, lyrics_plugin, found, expected
256+
):
257+
monkeypatch.setattr(lyrics_plugin, "find_lyrics", lambda _: found)
258+
item = helper.create_item(id=1, lyrics="old")
259+
260+
lyrics_plugin.add_item_lyrics(item, False)
261+
262+
assert item.lyrics == expected
263+
235264

236265
class LyricsBackendTest(LyricsPluginMixin):
237266
@pytest.fixture
@@ -281,8 +310,13 @@ def _patch_google_search(self, requests_mock, lyrics_page):
281310

282311
def test_backend_source(self, lyrics_plugin, lyrics_page: LyricsPage):
283312
"""Test parsed lyrics from each of the configured lyrics pages."""
284-
lyrics_info = lyrics_plugin.get_lyrics(
285-
lyrics_page.artist, lyrics_page.track_title, "", 186
313+
lyrics_info = lyrics_plugin.find_lyrics(
314+
Item(
315+
artist=lyrics_page.artist,
316+
title=lyrics_page.track_title,
317+
album="",
318+
length=186.0,
319+
)
286320
)
287321

288322
assert lyrics_info

0 commit comments

Comments
 (0)