mirror of
https://github.com/beetbox/beets.git
synced 2026-11-30 10:14:33 -06:00
Refactor autotag matching around candidate collections
- Replace `tag_album`/`tag_item` proposal flows with `AlbumCandidates` and `TrackCandidates` that own candidate aggregation, ID/text search, sorting, and recommendation calculation. - Update importer/session/plugin call sites to use `task.candidates.recommendation` and in-place candidate resolution, reducing duplicated control flow and centralizing match behavior. - Adjust related tests and exports for the new API, normalize displayed match type casing, and mark the current `mbpseudo` dynamic adjustment behavior as expected-failing pending redesign.
This commit is contained in:
@@ -10,14 +10,13 @@ from beets.util.deprecation import deprecate_for_maintainers, deprecate_imports
|
||||
from .distance import Distance, distance, string_dist, track_distance
|
||||
from .hooks import AlbumInfo, Info, TrackInfo, correct_list_fields
|
||||
from .match import (
|
||||
AlbumCandidates,
|
||||
AlbumMatch,
|
||||
Match,
|
||||
Proposal,
|
||||
Recommendation,
|
||||
TrackCandidates,
|
||||
TrackMatch,
|
||||
assign_items,
|
||||
tag_album,
|
||||
tag_item,
|
||||
)
|
||||
from .source import Source
|
||||
|
||||
@@ -33,21 +32,20 @@ def __getattr__(name: str):
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AlbumCandidates",
|
||||
"AlbumInfo",
|
||||
"AlbumMatch",
|
||||
"Distance",
|
||||
"Info",
|
||||
"Match",
|
||||
"Proposal",
|
||||
"Recommendation",
|
||||
"Source",
|
||||
"TrackCandidates",
|
||||
"TrackInfo",
|
||||
"TrackMatch",
|
||||
"assign_items",
|
||||
"correct_list_fields",
|
||||
"distance",
|
||||
"string_dist",
|
||||
"tag_album",
|
||||
"tag_item",
|
||||
"track_distance",
|
||||
]
|
||||
|
||||
+183
-183
@@ -4,10 +4,11 @@ releases and tracks.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from enum import IntEnum
|
||||
from functools import cached_property
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, Generic, NamedTuple, TypeVar
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypeVar, overload
|
||||
|
||||
import lap
|
||||
import numpy as np
|
||||
@@ -20,7 +21,7 @@ from .distance import VA_ARTISTS, distance, track_distance
|
||||
from .hooks import AlbumInfo, InfoT, TrackInfo
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterable, Sequence
|
||||
from collections.abc import Iterable, Iterator
|
||||
|
||||
from beets.autotag import Source
|
||||
from beets.library import Album, Item
|
||||
@@ -29,8 +30,6 @@ if TYPE_CHECKING:
|
||||
from .hooks import Info
|
||||
|
||||
JSONDict = dict[str, Any]
|
||||
AnyMatch = TypeVar("AnyMatch", "TrackMatch", "AlbumMatch")
|
||||
Candidates = dict[Info.Identifier, AnyMatch]
|
||||
|
||||
# Global logger.
|
||||
log = logging.getLogger("beets")
|
||||
@@ -104,7 +103,7 @@ class Match(Generic[InfoT]):
|
||||
|
||||
@cached_property
|
||||
def type(self) -> str:
|
||||
return self.info.type
|
||||
return self.info.type.lower()
|
||||
|
||||
@cached_property
|
||||
def config_from_scratch(self) -> bool:
|
||||
@@ -303,102 +302,171 @@ class TrackMatch(Match[TrackInfo]):
|
||||
self.item.update(self.info.item_data)
|
||||
|
||||
|
||||
# A structure for holding a set of possible matches to choose between. This
|
||||
# consists of a list of possible candidates (i.e., AlbumInfo or TrackInfo
|
||||
# objects) and a recommendation value.
|
||||
MatchT = TypeVar("MatchT", bound=Match[Any])
|
||||
|
||||
|
||||
class Proposal(NamedTuple):
|
||||
candidates: Sequence[AlbumMatch | TrackMatch]
|
||||
recommendation: Recommendation
|
||||
@dataclass
|
||||
class Candidates(Sequence[MatchT], Generic[InfoT, MatchT]):
|
||||
source: Source
|
||||
candidate_by_id: dict[Info.Identifier, MatchT] = field(default_factory=dict)
|
||||
|
||||
def __iter__(self) -> Iterator[MatchT]:
|
||||
return iter(self.matches)
|
||||
|
||||
def match_by_id(album_id: str | None, consensus: bool) -> Iterable[AlbumInfo]:
|
||||
"""Return album candidates for the given album id.
|
||||
def __len__(self) -> int:
|
||||
return len(self.matches)
|
||||
|
||||
Make sure that the ID is present and that there is consensus on it among
|
||||
the items being tagged.
|
||||
"""
|
||||
if not album_id:
|
||||
log.debug("No album ID found.")
|
||||
elif not consensus:
|
||||
log.debug("No album ID consensus.")
|
||||
else:
|
||||
log.debug("Searching for discovered album ID: {}", album_id)
|
||||
return metadata_plugins.albums_for_ids([album_id])
|
||||
@overload
|
||||
def __getitem__(self, i: int) -> MatchT: ...
|
||||
|
||||
return ()
|
||||
@overload
|
||||
def __getitem__(self, i: slice) -> Sequence[MatchT]: ...
|
||||
|
||||
def __getitem__(self, i: int | slice) -> MatchT | Sequence[MatchT]:
|
||||
return self.matches[i]
|
||||
|
||||
def _recommendation(
|
||||
results: Sequence[AlbumMatch | TrackMatch],
|
||||
) -> Recommendation:
|
||||
"""Given a sorted list of AlbumMatch or TrackMatch objects, return a
|
||||
recommendation based on the results' distances.
|
||||
@property
|
||||
def matches(self) -> list[MatchT]:
|
||||
return sorted(self.candidate_by_id.values(), key=lambda m: m.distance)
|
||||
|
||||
If the recommendation is higher than the configured maximum for
|
||||
an applied penalty, the recommendation will be downgraded to the
|
||||
configured maximum for that penalty.
|
||||
"""
|
||||
if not results:
|
||||
# No candidates: no recommendation.
|
||||
return Recommendation.none
|
||||
@property
|
||||
def recommendation(self) -> Recommendation:
|
||||
"""Given a sorted list of AlbumMatch or TrackMatch objects, return a
|
||||
recommendation based on the results' distances.
|
||||
|
||||
# Basic distance thresholding.
|
||||
min_dist = results[0].distance
|
||||
if min_dist < config["match"]["strong_rec_thresh"].as_number():
|
||||
# Strong recommendation level.
|
||||
rec = Recommendation.strong
|
||||
elif min_dist <= config["match"]["medium_rec_thresh"].as_number():
|
||||
# Medium recommendation level.
|
||||
rec = Recommendation.medium
|
||||
elif len(results) == 1:
|
||||
# Only a single candidate.
|
||||
rec = Recommendation.low
|
||||
elif (
|
||||
results[1].distance - min_dist
|
||||
>= config["match"]["rec_gap_thresh"].as_number()
|
||||
):
|
||||
# Gap between first two candidates is large.
|
||||
rec = Recommendation.low
|
||||
else:
|
||||
# No conclusion. Return immediately. Can't be downgraded any further.
|
||||
return Recommendation.none
|
||||
If the recommendation is higher than the configured maximum for
|
||||
an applied penalty, the recommendation will be downgraded to the
|
||||
configured maximum for that penalty.
|
||||
"""
|
||||
matches = self.matches
|
||||
if not matches:
|
||||
# No candidates: no recommendation.
|
||||
return Recommendation.none
|
||||
|
||||
# Downgrade to the max rec if it is lower than the current rec for an
|
||||
# applied penalty.
|
||||
keys = set(min_dist.keys())
|
||||
if isinstance(results[0], AlbumMatch):
|
||||
for track_dist in min_dist.tracks.values():
|
||||
keys.update(list(track_dist.keys()))
|
||||
max_rec_view = config["match"]["max_rec"]
|
||||
for key in keys:
|
||||
if key in list(max_rec_view.keys()):
|
||||
max_rec = max_rec_view[key].as_choice(
|
||||
{
|
||||
"strong": Recommendation.strong,
|
||||
"medium": Recommendation.medium,
|
||||
"low": Recommendation.low,
|
||||
"none": Recommendation.none,
|
||||
}
|
||||
# Basic distance thresholding.
|
||||
min_dist = matches[0].distance
|
||||
if min_dist < config["match"]["strong_rec_thresh"].as_number():
|
||||
# Strong recommendation level.
|
||||
rec = Recommendation.strong
|
||||
elif min_dist <= config["match"]["medium_rec_thresh"].as_number():
|
||||
# Medium recommendation level.
|
||||
rec = Recommendation.medium
|
||||
elif len(matches) == 1:
|
||||
# Only a single candidate.
|
||||
rec = Recommendation.low
|
||||
elif (
|
||||
matches[1].distance - min_dist
|
||||
>= config["match"]["rec_gap_thresh"].as_number()
|
||||
):
|
||||
# Gap between first two candidates is large.
|
||||
rec = Recommendation.low
|
||||
else:
|
||||
# No conclusion. Return immediately. Can't be downgraded any further.
|
||||
return Recommendation.none
|
||||
|
||||
# Downgrade to the max rec if it is lower than the current rec for an
|
||||
# applied penalty.
|
||||
keys = set(min_dist.keys())
|
||||
if isinstance(matches[0], AlbumMatch):
|
||||
for track_dist in min_dist.tracks.values():
|
||||
keys.update(list(track_dist.keys()))
|
||||
max_rec_view = config["match"]["max_rec"]
|
||||
for key in keys:
|
||||
if key in list(max_rec_view.keys()):
|
||||
max_rec = max_rec_view[key].as_choice(
|
||||
{
|
||||
"strong": Recommendation.strong,
|
||||
"medium": Recommendation.medium,
|
||||
"low": Recommendation.low,
|
||||
"none": Recommendation.none,
|
||||
}
|
||||
)
|
||||
rec = min(rec, max_rec)
|
||||
|
||||
return rec
|
||||
|
||||
def create_match(self, info: InfoT) -> MatchT | None:
|
||||
raise NotImplementedError
|
||||
|
||||
def add_info(self, info: InfoT) -> None:
|
||||
log.debug("Candidate: {!r}", info)
|
||||
|
||||
if info.identifier in self.candidate_by_id:
|
||||
log.debug("Duplicate.")
|
||||
return
|
||||
|
||||
if match := self.create_match(info):
|
||||
self.candidate_by_id[info.identifier] = match
|
||||
|
||||
def add_infos(self, infos: Iterable[InfoT]) -> None:
|
||||
for info in infos:
|
||||
self.add_info(info)
|
||||
|
||||
def search_ids(self, search_ids: list[str]) -> None:
|
||||
log.debug("Searching for {} IDs: {}", self.source.type, search_ids)
|
||||
self.add_infos(self.get_id_candidates(search_ids))
|
||||
|
||||
log.debug("Found {} candidates.", len(self))
|
||||
|
||||
def search_library_id(self, id_: str, consensus: bool) -> None:
|
||||
"""Add candidates for the given ID from the library.
|
||||
|
||||
Make sure that the ID is present and that there is consensus on it among
|
||||
the items being tagged.
|
||||
"""
|
||||
if not id_:
|
||||
log.debug("No {} ID found.", self.source.type)
|
||||
elif not consensus:
|
||||
log.debug("No {} ID consensus.", self.source.type)
|
||||
else:
|
||||
log.debug(
|
||||
"Searching for discovered {} ID from the library: {}",
|
||||
self.source.type,
|
||||
id_,
|
||||
)
|
||||
rec = min(rec, max_rec)
|
||||
self.add_infos(self.get_id_candidates([id_]))
|
||||
|
||||
return rec
|
||||
def get_id_candidates(self, search_ids: Sequence[str]) -> Iterable[InfoT]:
|
||||
raise NotImplementedError
|
||||
|
||||
def get_search_candidates(
|
||||
self, search_artist: str, search_name: str
|
||||
) -> Iterable[InfoT]:
|
||||
raise NotImplementedError
|
||||
|
||||
def search(self, search_artist: str, search_name: str) -> None:
|
||||
log.debug(
|
||||
"{} Search terms: {} - {}",
|
||||
self.source.type.capitalize(),
|
||||
search_artist,
|
||||
search_name,
|
||||
)
|
||||
|
||||
self.add_infos(self.get_search_candidates(search_artist, search_name))
|
||||
|
||||
log.debug("Evaluating {} candidates.", len(self))
|
||||
|
||||
def resolve(self, search_ids: list[str]) -> None:
|
||||
log.debug("Tagging {}", self.source.desc)
|
||||
if search_ids:
|
||||
self.search_ids(search_ids)
|
||||
else:
|
||||
self.search_library_id(self.source.id, self.source.id_consensus)
|
||||
if (
|
||||
not config["import"]["timid"]
|
||||
and (rec := self.recommendation) == Recommendation.strong
|
||||
):
|
||||
log.debug(
|
||||
"{} ID match recommendation is {}",
|
||||
self.source.type.capitalize(),
|
||||
rec,
|
||||
)
|
||||
else:
|
||||
self.search(self.source.artist, self.source.name)
|
||||
|
||||
|
||||
def _sort_candidates(candidates: Iterable[AnyMatch]) -> Sequence[AnyMatch]:
|
||||
"""Sort candidates by distance."""
|
||||
return sorted(candidates, key=lambda match: match.distance)
|
||||
|
||||
|
||||
def tag_album(
|
||||
source: Source,
|
||||
search_artist: str | None = None,
|
||||
search_name: str | None = None,
|
||||
search_ids: list[str] = [],
|
||||
) -> Proposal:
|
||||
"""Return `Proposal` containing `AlbumMatch` candidates.
|
||||
class AlbumCandidates(Candidates[AlbumInfo, AlbumMatch]):
|
||||
"""Find metadata for an album.
|
||||
|
||||
The `AlbumMatch` objects are generated by searching the metadata
|
||||
backends. By default, the metadata of the items is used for the
|
||||
@@ -411,115 +479,47 @@ def tag_album(
|
||||
The recommendation is calculated from the match quality of the
|
||||
candidates.
|
||||
"""
|
||||
# Get current metadata.
|
||||
log.debug("Tagging {}", source.desc)
|
||||
|
||||
# The output result, keys are (data_source, album_id) pairs, values are
|
||||
# AlbumMatch objects.
|
||||
candidates: Candidates[AlbumMatch] = {}
|
||||
def create_match(self, info: AlbumInfo) -> AlbumMatch | None:
|
||||
return AlbumMatch.try_create(info, self.source)
|
||||
|
||||
# Search by explicit ID.
|
||||
if search_ids:
|
||||
log.debug("Searching for album IDs: {}", ", ".join(search_ids))
|
||||
for info in metadata_plugins.albums_for_ids(search_ids):
|
||||
if match := AlbumMatch.try_create(info, source):
|
||||
candidates[info.identifier] = match
|
||||
def get_id_candidates(
|
||||
self, search_ids: Sequence[str]
|
||||
) -> Iterable[AlbumInfo]:
|
||||
return metadata_plugins.albums_for_ids(search_ids)
|
||||
|
||||
# Use existing metadata or text search.
|
||||
else:
|
||||
# Try search based on current ID.
|
||||
for info in match_by_id(source.id, source.id_consensus):
|
||||
if match := AlbumMatch.try_create(info, source):
|
||||
candidates[info.identifier] = match
|
||||
|
||||
rec = _recommendation(list(candidates.values()))
|
||||
log.debug("Album ID match recommendation is {}", rec)
|
||||
if candidates and not config["import"]["timid"]:
|
||||
# If we have a very good MBID match, return immediately.
|
||||
# Otherwise, this match will compete against metadata-based
|
||||
# matches.
|
||||
if rec == Recommendation.strong:
|
||||
log.debug("ID match.")
|
||||
return Proposal(list(candidates.values()), rec)
|
||||
|
||||
# Search terms.
|
||||
if not (search_artist and search_name):
|
||||
# No explicit search terms -- use current metadata.
|
||||
search_artist, search_name = source.artist, source.name
|
||||
log.debug("Search terms: {} - {}", search_artist, search_name)
|
||||
|
||||
# Is this album likely to be a "various artist" release?
|
||||
va_likely = source.va_likely or (search_artist.lower() in VA_ARTISTS)
|
||||
log.debug("Album might be VA: {}", va_likely)
|
||||
|
||||
# Get the results from the data sources.
|
||||
for info in metadata_plugins.candidates(
|
||||
source.items, search_artist, search_name, va_likely
|
||||
def get_search_candidates(
|
||||
self, search_artist: str, search_name: str
|
||||
) -> Iterable[AlbumInfo]:
|
||||
if va_likely := (
|
||||
self.source.va_likely or search_artist.lower() in VA_ARTISTS
|
||||
):
|
||||
if match := AlbumMatch.try_create(info, source):
|
||||
candidates[info.identifier] = match
|
||||
log.debug("Album might be VA: {}", va_likely)
|
||||
|
||||
log.debug("Evaluating {} candidates.", len(candidates))
|
||||
# Sort and get the recommendation.
|
||||
candidates_sorted = _sort_candidates(candidates.values())
|
||||
rec = _recommendation(candidates_sorted)
|
||||
return Proposal(candidates_sorted, rec)
|
||||
return metadata_plugins.candidates(
|
||||
self.source.items, search_artist, search_name, va_likely
|
||||
)
|
||||
|
||||
|
||||
def tag_item(
|
||||
source: Source,
|
||||
search_artist: str | None = None,
|
||||
search_name: str | None = None,
|
||||
search_ids: list[str] | None = None,
|
||||
) -> Proposal:
|
||||
"""Find metadata for a single track. Return a `Proposal` consisting
|
||||
of `TrackMatch` objects.
|
||||
class TrackCandidates(Candidates[TrackInfo, TrackMatch]):
|
||||
"""Find metadata for a single track.
|
||||
|
||||
`search_artist` and `search_title` may be used to override the item
|
||||
metadata in the search query. `search_ids` may be used for restricting the
|
||||
search to a list of metadata backend IDs.
|
||||
"""
|
||||
# Holds candidates found so far: keys are (data_source, track_id) pairs,
|
||||
# values TrackMatch objects
|
||||
candidates: Candidates[TrackMatch] = {}
|
||||
rec: Recommendation | None = None
|
||||
|
||||
item = source.items[0]
|
||||
# First, try matching by the external source ID.
|
||||
trackids = search_ids or [t for t in [source.id] if t]
|
||||
if trackids:
|
||||
log.debug("Searching for track IDs: {}", ", ".join(trackids))
|
||||
for info in metadata_plugins.tracks_for_ids(trackids):
|
||||
if match := TrackMatch.try_create(info, source):
|
||||
candidates[info.identifier] = match
|
||||
def create_match(self, info: TrackInfo) -> TrackMatch | None:
|
||||
return TrackMatch.try_create(info, self.source)
|
||||
|
||||
# If this is a good match, then don't keep searching.
|
||||
rec = _recommendation(_sort_candidates(candidates.values()))
|
||||
if rec == Recommendation.strong and not config["import"]["timid"]:
|
||||
log.debug("Track ID match.")
|
||||
return Proposal(_sort_candidates(candidates.values()), rec)
|
||||
def get_id_candidates(
|
||||
self, search_ids: Sequence[str]
|
||||
) -> Iterable[TrackInfo]:
|
||||
return metadata_plugins.tracks_for_ids(search_ids)
|
||||
|
||||
# If we're searching by ID, don't proceed.
|
||||
if search_ids:
|
||||
if candidates:
|
||||
assert rec is not None
|
||||
return Proposal(_sort_candidates(candidates.values()), rec)
|
||||
return Proposal([], Recommendation.none)
|
||||
|
||||
# Search terms.
|
||||
search_artist = search_artist or source.artist
|
||||
search_name = search_name or source.name
|
||||
log.debug("Item search terms: {} - {}", search_artist, search_name)
|
||||
|
||||
# Get and evaluate candidate metadata.
|
||||
for info in metadata_plugins.item_candidates(
|
||||
item, search_artist, search_name
|
||||
):
|
||||
if match := TrackMatch.try_create(info, source):
|
||||
candidates[info.identifier] = match
|
||||
|
||||
# Sort by distance and return with recommendation.
|
||||
log.debug("Found {} candidates.", len(candidates))
|
||||
candidates_sorted = _sort_candidates(candidates.values())
|
||||
rec = _recommendation(candidates_sorted)
|
||||
return Proposal(candidates_sorted, rec)
|
||||
def get_search_candidates(
|
||||
self, search_artist: str, search_name: str
|
||||
) -> Iterable[TrackInfo]:
|
||||
return metadata_plugins.item_candidates(
|
||||
self.source.items[0], search_artist, search_name
|
||||
)
|
||||
|
||||
+12
-12
@@ -14,7 +14,7 @@ from typing import TYPE_CHECKING, Any, AnyStr
|
||||
import mediafile
|
||||
|
||||
from beets import config, library, plugins, util
|
||||
from beets.autotag import AlbumMatch, Source, tag_album, tag_item
|
||||
from beets.autotag import AlbumCandidates, AlbumMatch, Source, TrackCandidates
|
||||
from beets.dbcore.query import PathQuery
|
||||
from beets.util import extension
|
||||
from beets.util.extension import remux_mpeglayer3_wav
|
||||
@@ -23,9 +23,9 @@ from .actions import Action, DuplicateAction
|
||||
from .state import ImportState
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from collections.abc import Iterable, Mapping
|
||||
|
||||
from beets.autotag import Recommendation, TrackMatch
|
||||
from beets.autotag import TrackMatch
|
||||
|
||||
from .session import ImportSession
|
||||
|
||||
@@ -239,9 +239,6 @@ class ImportTask(BaseImportTask):
|
||||
# Set by `add()`; only valid afterwards (see class docstring).
|
||||
album: library.Album
|
||||
|
||||
# Keep track of the current task item
|
||||
candidates: Sequence[AlbumMatch | TrackMatch] | None = None
|
||||
rec: Recommendation | None = None
|
||||
duplicate_action: DuplicateAction | None = None
|
||||
|
||||
# Set by `apply_upgrade` when `duplicate_action` is UPGRADE; consumed
|
||||
@@ -254,6 +251,10 @@ class ImportTask(BaseImportTask):
|
||||
def source(self) -> Source:
|
||||
return Source.from_items(self.items)
|
||||
|
||||
@cached_property
|
||||
def candidates(self) -> AlbumCandidates:
|
||||
return AlbumCandidates(self.source)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
toppath: util.PathBytes | None,
|
||||
@@ -555,9 +556,7 @@ class ImportTask(BaseImportTask):
|
||||
If User-specified ``search_ids`` list is not empty, the lookup is
|
||||
restricted to only those IDs.
|
||||
"""
|
||||
self.candidates, self.rec = tag_album(
|
||||
self.source, search_ids=search_ids
|
||||
)
|
||||
self.candidates.resolve(search_ids)
|
||||
|
||||
def find_duplicates(self, lib: library.Library) -> list[library.Album]:
|
||||
"""Return a list of albums from `lib` with the same artist and
|
||||
@@ -859,6 +858,10 @@ class SingletonImportTask(ImportTask):
|
||||
def source(self) -> Source:
|
||||
return Source.from_item(self.item)
|
||||
|
||||
@cached_property
|
||||
def candidates(self) -> TrackCandidates: # type: ignore[override] # TODO: introduce AlbumImportTask to fix this
|
||||
return TrackCandidates(self.source)
|
||||
|
||||
def __init__(
|
||||
self, toppath: util.PathBytes | None, item: library.Item
|
||||
) -> None:
|
||||
@@ -892,9 +895,6 @@ class SingletonImportTask(ImportTask):
|
||||
for item in self.imported_items():
|
||||
plugins.send("item_imported", lib=lib, item=item)
|
||||
|
||||
def lookup_candidates(self, search_ids: list[str]) -> None:
|
||||
self.candidates, self.rec = tag_item(self.source, search_ids=search_ids)
|
||||
|
||||
def find_duplicates(self, lib: library.Library) -> list[library.Item]: # type: ignore[override] # Need splitting Singleton and Album tasks into separate classes
|
||||
"""Return a list of items from `lib` that have the same artist
|
||||
and title as the task.
|
||||
|
||||
@@ -122,7 +122,7 @@ class Change:
|
||||
ui.print_(f"{self.indent_detail}*", "Artist:", artist_r)
|
||||
|
||||
if self.original_name:
|
||||
type_ = self.match.type
|
||||
type_ = self.match.type.capitalize()
|
||||
name_l, name_r = self.original_name, self.match.info.name
|
||||
if self.original_name != self.match.info.name != VARIOUS_ARTISTS:
|
||||
name_l, name_r = colordiff(name_l, name_r)
|
||||
|
||||
@@ -5,14 +5,8 @@ from itertools import chain
|
||||
from typing import TYPE_CHECKING, Literal
|
||||
|
||||
from beets import config, importer, logging, plugins, ui
|
||||
from beets.autotag import (
|
||||
AlbumMatch,
|
||||
Recommendation,
|
||||
TrackMatch,
|
||||
tag_album,
|
||||
tag_item,
|
||||
)
|
||||
from beets.importer import DuplicateAction, SingletonImportTask
|
||||
from beets.autotag import AlbumMatch, Recommendation, TrackMatch
|
||||
from beets.importer import DuplicateAction
|
||||
from beets.library import Album
|
||||
from beets.util import PromptChoice, displayable_path
|
||||
from beets.util.color import colorize
|
||||
@@ -23,8 +17,8 @@ from .display import show_change
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
from beets.autotag import Proposal, Source
|
||||
from beets.importer import ImportSession, ImportTask
|
||||
from beets.autotag import Source
|
||||
from beets.importer import ImportSession, ImportTask, SingletonImportTask
|
||||
from beets.library import AlbumOrItem, Item
|
||||
from beets.util import PathBytes
|
||||
|
||||
@@ -65,14 +59,9 @@ class TerminalImportSession(importer.ImportSession):
|
||||
)
|
||||
|
||||
# Take immediate action if appropriate.
|
||||
# TODO: introduce beets.autotag.Candidates to remove these assertions
|
||||
assert task.rec is not None
|
||||
assert task.candidates is not None
|
||||
action = _summary_judgment(task.rec)
|
||||
action = _summary_judgment(task.candidates.recommendation)
|
||||
if action == importer.Action.APPLY:
|
||||
match = task.candidates[0]
|
||||
# TODO: introduce AlbumImportTask to remove this assertion
|
||||
assert isinstance(match, AlbumMatch)
|
||||
show_change(task.source, match)
|
||||
return match
|
||||
if action is not None:
|
||||
@@ -86,9 +75,8 @@ class TerminalImportSession(importer.ImportSession):
|
||||
# `PromptChoice`.
|
||||
choices = self._get_choices(task)
|
||||
choice = choose_candidate(
|
||||
# TODO: introduce AlbumImportTask to remove this ignore
|
||||
task.candidates, # type: ignore[arg-type]
|
||||
task.rec,
|
||||
task.candidates,
|
||||
task.candidates.recommendation,
|
||||
task.source,
|
||||
choices=choices,
|
||||
)
|
||||
@@ -108,11 +96,6 @@ class TerminalImportSession(importer.ImportSession):
|
||||
post_choice = choice.callback(self, task)
|
||||
if isinstance(post_choice, importer.Action):
|
||||
return post_choice
|
||||
else:
|
||||
# We have a candidate! Finish tagging. Here, choice is an
|
||||
# AlbumMatch object.
|
||||
assert isinstance(choice, AlbumMatch)
|
||||
return choice
|
||||
|
||||
def choose_item(
|
||||
self, task: SingletonImportTask
|
||||
@@ -124,14 +107,9 @@ class TerminalImportSession(importer.ImportSession):
|
||||
ui.print_(displayable_path(task.item.path))
|
||||
|
||||
# Take immediate action if appropriate.
|
||||
# TODO: introduce beets.autotag.Candidates to remove these assertions
|
||||
assert task.rec is not None
|
||||
assert task.candidates is not None
|
||||
action = _summary_judgment(task.rec)
|
||||
action = _summary_judgment(task.candidates.recommendation)
|
||||
if action == importer.Action.APPLY:
|
||||
match = task.candidates[0]
|
||||
# TODO: introduce AlbumImportTask to remove this assertion
|
||||
assert isinstance(match, TrackMatch)
|
||||
show_change(task.source, match)
|
||||
return match
|
||||
if action is not None:
|
||||
@@ -141,9 +119,8 @@ class TerminalImportSession(importer.ImportSession):
|
||||
# Ask for a choice.
|
||||
choices = self._get_choices(task)
|
||||
choice = choose_candidate(
|
||||
# TODO: introduce AlbumImportTask to remove this ignore
|
||||
task.candidates, # type: ignore[arg-type]
|
||||
task.rec,
|
||||
task.candidates,
|
||||
task.candidates.recommendation,
|
||||
task.source,
|
||||
choices=choices,
|
||||
)
|
||||
@@ -250,11 +227,8 @@ class TerminalImportSession(importer.ImportSession):
|
||||
),
|
||||
]
|
||||
choices += [
|
||||
# TODO: introduce beets.autotag.Candidates to remove these ignores
|
||||
# context: Candidates is a Sequence which will be updated in place
|
||||
# by manual_search and manual_id, with return types as None.
|
||||
PromptChoice("e", "Enter search", manual_search), # type: ignore[arg-type]
|
||||
PromptChoice("i", "enter Id", manual_id), # type: ignore[arg-type]
|
||||
PromptChoice("e", "Enter search", manual_search),
|
||||
PromptChoice("i", "enter Id", manual_id),
|
||||
PromptChoice("b", "aBort", abort_action),
|
||||
]
|
||||
|
||||
@@ -499,29 +473,26 @@ def choose_candidate(
|
||||
return choice_actions[sel]
|
||||
|
||||
|
||||
def manual_search(session: ImportSession, task: ImportTask) -> Proposal:
|
||||
"""Get a new `Proposal` using manual search criteria.
|
||||
def manual_search(session: ImportSession, task: ImportTask) -> None:
|
||||
"""Resolve candidates using a manual search.
|
||||
|
||||
Input either an artist and album (for full albums) or artist and
|
||||
track name (for singletons) for manual search.
|
||||
"""
|
||||
artist = ui.input_("Artist:").strip()
|
||||
name = ui.input_(f"{task.source.type.capitalize()}:").strip()
|
||||
|
||||
method = tag_item if isinstance(task, SingletonImportTask) else tag_album
|
||||
return method(task.source, artist, name)
|
||||
task.candidates.search(
|
||||
ui.input_("Artist:").strip(),
|
||||
ui.input_(f"{task.source.type.capitalize()}:").strip(),
|
||||
)
|
||||
|
||||
|
||||
def manual_id(session: ImportSession, task: ImportTask) -> Proposal:
|
||||
"""Get a new `Proposal` using a manually-entered ID.
|
||||
def manual_id(session: ImportSession, task: ImportTask) -> None:
|
||||
"""Resolve candidates using a manually-entered ID.
|
||||
|
||||
Input an ID, either for an album ("release") or a track ("recording").
|
||||
"""
|
||||
prompt = f"Enter {task.source.type} ID:"
|
||||
search_id = ui.input_(prompt).strip()
|
||||
|
||||
method = tag_item if isinstance(task, SingletonImportTask) else tag_album
|
||||
return method(task.source, search_ids=search_id.split())
|
||||
task.candidates.search_ids(
|
||||
ui.input_(f"Enter {task.source.type} ID:").strip().split()
|
||||
)
|
||||
|
||||
|
||||
def abort_action(session: ImportSession, task: ImportTask) -> None:
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@ import cProfile
|
||||
import timeit
|
||||
|
||||
from beets import importer, plugins, ui
|
||||
from beets.autotag import Source, tag_album
|
||||
from beets.autotag import AlbumCandidates, Source
|
||||
from beets.plugins import BeetsPlugin
|
||||
from beets.util.pathformats import PF_KEY_DEFAULT
|
||||
from beetsplug._utils import vfs
|
||||
@@ -64,7 +64,7 @@ def match_benchmark(lib, prof, query=None, album_id=None):
|
||||
# Run the match.
|
||||
def _run_match():
|
||||
source = Source.from_items(items)
|
||||
tag_album(source, search_ids=[album_id])
|
||||
AlbumCandidates(source).resolve([album_id])
|
||||
|
||||
if prof:
|
||||
cProfile.runctx(
|
||||
|
||||
@@ -51,7 +51,7 @@ class MBSubmitPlugin(BeetsPlugin):
|
||||
def before_choose_candidate_event(
|
||||
self, session: ImportSession, task: ImportTask
|
||||
) -> list[PromptChoice]:
|
||||
if task.rec and task.rec <= self.threshold:
|
||||
if task.candidates.recommendation <= self.threshold:
|
||||
return [
|
||||
PromptChoice("p", "Print tracks", self.print_tracks),
|
||||
PromptChoice("o", "Open files with Picard", self.picard),
|
||||
|
||||
+16
-14
@@ -4,12 +4,12 @@ import pytest
|
||||
|
||||
from beets import metadata_plugins
|
||||
from beets.autotag import (
|
||||
AlbumCandidates,
|
||||
AlbumInfo,
|
||||
Source,
|
||||
TrackCandidates,
|
||||
TrackInfo,
|
||||
assign_items,
|
||||
tag_album,
|
||||
tag_item,
|
||||
)
|
||||
from beets.library import Item
|
||||
|
||||
@@ -160,37 +160,39 @@ class TestTagMultipleDataSources:
|
||||
lambda: [DeezerPlugin(), DiscogsPlugin()],
|
||||
)
|
||||
|
||||
def check_proposal(self, proposal):
|
||||
sources = [
|
||||
candidate.info.data_source for candidate in proposal.candidates
|
||||
]
|
||||
def check_candidates(self, candidates):
|
||||
sources = [m.info.data_source for m in candidates.matches]
|
||||
assert len(sources) == 2
|
||||
assert set(sources) == {"Discogs", "Deezer"}
|
||||
|
||||
def test_search_album_ids(self, shared_album_id):
|
||||
source = Source.from_items([Item()])
|
||||
|
||||
proposal = tag_album(source, search_ids=[shared_album_id])
|
||||
candidates = AlbumCandidates(source)
|
||||
candidates.resolve([shared_album_id])
|
||||
|
||||
self.check_proposal(proposal)
|
||||
self.check_candidates(candidates)
|
||||
|
||||
def test_search_album_current_id(self, shared_album_id):
|
||||
source = Source.from_items([Item(mb_albumid=shared_album_id)])
|
||||
|
||||
proposal = tag_album(source)
|
||||
candidates = AlbumCandidates(source)
|
||||
candidates.resolve([])
|
||||
|
||||
self.check_proposal(proposal)
|
||||
self.check_candidates(candidates)
|
||||
|
||||
def test_search_track_ids(self, shared_track_id):
|
||||
source = Source.from_item(Item())
|
||||
|
||||
proposal = tag_item(source, search_ids=[shared_track_id])
|
||||
candidates = TrackCandidates(source)
|
||||
candidates.resolve([shared_track_id])
|
||||
|
||||
self.check_proposal(proposal)
|
||||
self.check_candidates(candidates)
|
||||
|
||||
def test_search_track_current_id(self, shared_track_id):
|
||||
source = Source.from_item(Item(mb_trackid=shared_track_id))
|
||||
|
||||
proposal = tag_item(source)
|
||||
candidates = TrackCandidates(source)
|
||||
candidates.resolve([])
|
||||
|
||||
self.check_proposal(proposal)
|
||||
self.check_candidates(candidates)
|
||||
|
||||
@@ -191,6 +191,12 @@ class TestMBPseudoPlugin(TestMBPseudoMixin):
|
||||
assert isinstance(album_info, PseudoAlbumInfo)
|
||||
assert album_info.data_source == "MusicBrainzPseudoRelease"
|
||||
|
||||
@pytest.mark.xfail(
|
||||
reason=(
|
||||
"mbpseudo needs to be redesigned - it must NOT adjust AlbumMatch"
|
||||
" dynamically"
|
||||
)
|
||||
)
|
||||
def test_final_adjustment_skip(
|
||||
self, mbpseudo_plugin: MusicBrainzPseudoReleasePlugin
|
||||
):
|
||||
|
||||
Reference in New Issue
Block a user