Skip to content

Commit ffd1b8a

Browse files
committed
Improve flags structure and add tests
1 parent e3af029 commit ffd1b8a

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
@@ -44,7 +44,7 @@
4444
from logging import Logger
4545

4646
from beets.importer import ImportTask
47-
from beets.library import Item
47+
from beets.library import Item, Library
4848

4949
from ._typing import (
5050
GeniusAPI,
@@ -950,7 +950,6 @@ def translator(self) -> Translator | None:
950950

951951
def __init__(self):
952952
super().__init__()
953-
self.import_stages = [self.imported]
954953
self.config.add(
955954
{
956955
"auto": True,
@@ -969,6 +968,7 @@ def __init__(self):
969968
"fallback": None,
970969
"force": False,
971970
"local": False,
971+
"print": False,
972972
"synced": False,
973973
# Musixmatch is disabled by default as they are currently blocking
974974
# requests with the beets user agent.
@@ -982,14 +982,16 @@ def __init__(self):
982982
self.config["google_engine_ID"].redact = True
983983
self.config["genius_api_key"].redact = True
984984

985+
if self.config["auto"]:
986+
self.import_stages = [self.imported]
987+
985988
def commands(self):
986989
cmd = ui.Subcommand("lyrics", help="fetch song lyrics")
987990
cmd.parser.add_option(
988991
"-p",
989992
"--print",
990-
dest="printlyr",
991993
action="store_true",
992-
default=False,
994+
default=self.config["print"].get(),
993995
help="print lyrics to console",
994996
)
995997
cmd.parser.add_option(
@@ -1004,34 +1006,27 @@ def commands(self):
10041006
cmd.parser.add_option(
10051007
"-f",
10061008
"--force",
1007-
dest="force_refetch",
10081009
action="store_true",
1009-
default=False,
1010+
default=self.config["force"].get(),
10101011
help="always re-download lyrics",
10111012
)
10121013
cmd.parser.add_option(
10131014
"-l",
10141015
"--local",
1015-
dest="local_only",
10161016
action="store_true",
1017-
default=False,
1017+
default=self.config["local"].get(),
10181018
help="do not fetch missing lyrics",
10191019
)
10201020

1021-
def func(lib, opts, args):
1021+
def func(lib: Library, opts, args) -> None:
10221022
# The "write to files" option corresponds to the
10231023
# import_write config value.
1024-
items = list(lib.items(ui.decargs(args)))
1024+
self.config.set(vars(opts))
1025+
items = list(lib.items(args))
10251026
for item in items:
1026-
if not opts.local_only and not self.config["local"]:
1027-
self.fetch_item_lyrics(
1028-
item,
1029-
ui.should_write(),
1030-
opts.force_refetch or self.config["force"],
1031-
)
1032-
if item.lyrics:
1033-
if opts.printlyr:
1034-
ui.print_(item.lyrics)
1027+
self.add_item_lyrics(item, ui.should_write())
1028+
if item.lyrics and opts.print:
1029+
ui.print_(item.lyrics)
10351030

10361031
if opts.rest_directory and (
10371032
items := [i for i in items if i.lyrics]
@@ -1043,32 +1038,34 @@ def func(lib, opts, args):
10431038

10441039
def imported(self, _, task: ImportTask) -> None:
10451040
"""Import hook for fetching lyrics automatically."""
1046-
if self.config["auto"]:
1047-
for item in task.imported_items():
1048-
self.fetch_item_lyrics(item, False, self.config["force"])
1041+
for item in task.imported_items():
1042+
self.add_item_lyrics(item, False)
1043+
1044+
def find_lyrics(self, item: Item) -> str:
1045+
album, length = item.album, round(item.length)
1046+
matches = (
1047+
[
1048+
lyrics
1049+
for t in titles
1050+
if (lyrics := self.get_lyrics(a, t, album, length))
1051+
]
1052+
for a, titles in search_pairs(item)
1053+
)
10491054

1050-
def fetch_item_lyrics(self, item: Item, write: bool, force: bool) -> None:
1055+
return "\n\n---\n\n".join(next(filter(None, matches), []))
1056+
1057+
def add_item_lyrics(self, item: Item, write: bool) -> None:
10511058
"""Fetch and store lyrics for a single item. If ``write``, then the
10521059
lyrics will also be written to the file itself.
10531060
"""
1054-
# Skip if the item already has lyrics.
1055-
if not force and item.lyrics:
1056-
self.info("🔵 Lyrics already present: {}", item)
1061+
if self.config["local"]:
10571062
return
10581063

1059-
lyrics_matches = []
1060-
album, length = item.album, round(item.length)
1061-
for artist, titles in search_pairs(item):
1062-
lyrics_matches = [
1063-
self.get_lyrics(artist, title, album, length)
1064-
for title in titles
1065-
]
1066-
if any(lyrics_matches):
1067-
break
1068-
1069-
lyrics = "\n\n---\n\n".join(filter(None, lyrics_matches))
1064+
if not self.config["force"] and item.lyrics:
1065+
self.info("🔵 Lyrics already present: {}", item)
1066+
return
10701067

1071-
if lyrics:
1068+
if lyrics := self.find_lyrics(item):
10721069
self.info("🟢 Found lyrics: {0}", item)
10731070
if translator := self.translator:
10741071
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
@@ -75,6 +76,7 @@ The available options are:
7576
- **google_engine_ID**: The custom search engine to use.
7677
Default: The `beets custom search engine`_, which gathers an updated list of
7778
sources known to be scrapeable.
79+
- **print**: Print lyrics to the console.
7880
- **sources**: List of sources to search for lyrics. An asterisk ``*`` expands
7981
to all available sources. The ``google`` source will be automatically
8082
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",
@@ -233,6 +241,27 @@ def test_error_handling(
233241
assert last_log
234242
assert re.search(expected_log_match, last_log, re.I)
235243

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

237266
class LyricsBackendTest(LyricsPluginMixin):
238267
@pytest.fixture
@@ -282,8 +311,13 @@ def _patch_google_search(self, requests_mock, lyrics_page):
282311

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

289323
assert lyrics_info

0 commit comments

Comments
 (0)