Files
beets/beetsplug/_utils/playcount.py
Maxr1998 fce53eafdf playcount: prefer exact title/artist/album matches over substring matches
Try to match the exact title and artist/album first (case-insensitive via StringQuery),
only then fall back to the previous substring matching.

This helps in cases where multiple variants of a song with distinct listen counts exist, like "Song" and "Song (inst.)" or "Song (Japanese ver.)".
This commit stops "Song" from also updating those separate variants if an exact match of "Song" exists.

Nonetheless, if the library only has an item named "Song (feat. Artist)", "Song" will still update its play count through the substring match.
2026-09-07 08:20:07 +01:00

122 lines
3.2 KiB
Python

from __future__ import annotations
from typing import TYPE_CHECKING, TypedDict
from typing_extensions import NotRequired
from beets.dbcore import AndQuery, MatchQuery, OrQuery
from beets.dbcore.query import StringQuery, SubstringQuery
if TYPE_CHECKING:
from collections.abc import Sequence
from beets.dbcore import Query
from beets.library import Item, Library
from beets.logging import BeetsLogger
class Track(TypedDict):
mbid: str | None
name: str
artist: str
playcount: int
album: NotRequired[str | None]
def get_items(lib: Library, track: Track, log: BeetsLogger) -> Sequence[Item]:
mbid = track["mbid"]
if mbid:
items = list(lib.items(MatchQuery("mb_trackid", mbid)))
if items:
# Prefer MBID if there is a match
return items
artist, title = track["artist"], track["name"]
album = track.get("album") or ""
log.debug("query: {} - {} ({})", artist, title, album)
# Try exact match first
title_query = OrQuery(
[
StringQuery("title", title),
# try a right single quotation mark instead of an apostrophe
StringQuery("title", title.replace("'", "\u2019")),
]
)
or_queries: list[Query] = [StringQuery("artist", artist)]
if album:
or_queries.append(StringQuery("album", album))
items = list(lib.items(AndQuery([title_query, OrQuery(or_queries)])))
if items:
return items
# Fall back to substring matches
title_query = OrQuery(
[
SubstringQuery("title", title),
# try a right single quotation mark instead of an apostrophe
SubstringQuery("title", title.replace("'", "\u2019")),
]
)
or_queries = [SubstringQuery("artist", artist)]
if album:
or_queries.append(SubstringQuery("album", album))
return list(lib.items(AndQuery([title_query, OrQuery(or_queries)])))
def process_track(
lib: Library, track: Track, log: BeetsLogger, source: str
) -> bool:
items = get_items(lib, track, log)
if not items:
return False
new_count = track["playcount"]
field = f"{source}_play_count"
for song in items:
count = int(song.get(field, 0))
log.debug(
"match: {0.artist} - {0.title} ({0.album}) updating:"
" {1} {2} => {3}",
song,
field,
count,
new_count,
)
song[field] = new_count
song.store()
return True
def update_play_counts(
lib: Library, tracks: Sequence[Track], log: BeetsLogger, source: str
) -> tuple[int, int]:
total = len(tracks)
total_found = 0
total_fails = 0
log.info("Received {} tracks in this page, processing...", total)
with lib.transaction():
for i, track in enumerate(tracks, 1):
if i % 250 == 0:
log.info("Processing track {}/{} ...", i, total)
if process_track(lib, track, log, source):
total_found += 1
else:
total_fails += 1
if total_fails > 0:
log.info(
"Acquired {}/{} play-counts ({} unknown)",
total_found,
total,
total_fails,
)
return total_found, total_fails