From 2c4c42a42b45e19a2bffcb42fe6e994d53e18bdb Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Tue, 6 Oct 2026 23:37:54 +0100 Subject: [PATCH] Find album art by MusicBrainz ID (SCR-6) Corrections accept a release MBID as well as a release-group MBID, and the worker uses a scrobble's recording MBID to find the release-group before falling back to the text search. Counts matched/missed recording lookups. Co-Authored-By: Claude Sonnet 5.5 --- docs/openapi.json | 13 ++- frontend/js/art-failures.js | 10 +- src/scrobbler/api/art.py | 4 +- src/scrobbler/metrics/__init__.py | 7 +- ...7d2f08a19e4_user_album_art_release_mbid.py | 25 +++++ src/scrobbler/models.py | 1 + src/scrobbler/schemas/__init__.py | 16 ++- src/scrobbler/services/art.py | 96 ++++++++++++---- tests/test_art.py | 106 +++++++++++++++++- 9 files changed, 250 insertions(+), 28 deletions(-) create mode 100644 src/scrobbler/migrations/versions/c7d2f08a19e4_user_album_art_release_mbid.py diff --git a/docs/openapi.json b/docs/openapi.json index b0fd646..bec1d92 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -1778,7 +1778,7 @@ } }, "summary": "Correct a failed lookup", - "description": "Queues a new lookup with different search text, or straight from a MusicBrainz\nrelease-group ID. The background worker resolves it; poll the failures list, or just\nfetch the art later. Replaces any earlier upload or correction of yours.", + "description": "Queues a new lookup with different search text, or straight from a MusicBrainz\nrelease-group or release ID. The background worker resolves it; poll the failures list, or just\nfetch the art later. Replaces any earlier upload or correction of yours.", "tags": [ "Art" ], @@ -4534,6 +4534,12 @@ "string", "null" ] + }, + "release_mbid": { + "type": [ + "string", + "null" + ] } }, "additionalProperties": false @@ -4567,6 +4573,11 @@ "type": "string", "format": "uuid", "description": "A MusicBrainz release-group ID; skips the search" + }, + "release_mbid": { + "type": "string", + "format": "uuid", + "description": "A MusicBrainz release ID, as an alternative to a release-group ID; skips the search" } }, "required": [ diff --git a/frontend/js/art-failures.js b/frontend/js/art-failures.js index ce2f5bb..a02c1ce 100644 --- a/frontend/js/art-failures.js +++ b/frontend/js/art-failures.js @@ -119,10 +119,11 @@ function albumRow(item) { correction.addEventListener("submit", (event) => { event.preventDefault(); const body = { artist, album }; - const { search_artist, search_album, release_group_mbid } = correction.elements; + const { search_artist, search_album, release_group_mbid, release_mbid } = correction.elements; if (search_artist.value.trim()) body.search_artist = search_artist.value.trim(); if (search_album.value.trim()) body.search_album = search_album.value.trim(); if (release_group_mbid.value.trim()) body.release_group_mbid = release_group_mbid.value.trim(); + if (release_mbid.value.trim()) body.release_mbid = release_mbid.value.trim(); act(() => api("/art/album/correction", { method: "PUT", body }), `Queued a corrected lookup for ${album}.`); }); @@ -165,6 +166,13 @@ function correctionForm(item, query) { "If you know it, paste the ID from the album's MusicBrainz page. It skips the search.", { placeholder: "00000000-0000-0000-0000-000000000000", pattern: "[0-9a-fA-F-]{36}" }, ), + field( + "release_mbid", + "MusicBrainz release ID (optional)", + own.release_mbid, + "Or a specific release's ID, if that's the one you have. Use either this or the release-group ID.", + { placeholder: "00000000-0000-0000-0000-000000000000", pattern: "[0-9a-fA-F-]{36}" }, + ), h("button", { type: "submit", class: "button" }, "Look it up"), ); } diff --git a/src/scrobbler/api/art.py b/src/scrobbler/api/art.py index f21c350..a4eff20 100644 --- a/src/scrobbler/api/art.py +++ b/src/scrobbler/api/art.py @@ -127,10 +127,11 @@ def correct_art(body): """Correct a failed lookup Queues a new lookup with different search text, or straight from a MusicBrainz - release-group ID. The background worker resolves it; poll the failures list, or just + release-group or release ID. The background worker resolves it; poll the failures list, or just fetch the art later. Replaces any earlier upload or correction of yours. """ mbid = body.get("release_group_mbid") + release_mbid = body.get("release_mbid") art.request_correction( g.user.id, body["artist"], @@ -138,6 +139,7 @@ def correct_art(body): body.get("search_artist"), body.get("search_album"), str(mbid) if mbid else None, + str(release_mbid) if release_mbid else None, ) return art.get_override(g.user.id, body["artist"], body["album"]) diff --git a/src/scrobbler/metrics/__init__.py b/src/scrobbler/metrics/__init__.py index 056573a..f4abe3a 100644 --- a/src/scrobbler/metrics/__init__.py +++ b/src/scrobbler/metrics/__init__.py @@ -172,9 +172,14 @@ art_override_actions_total = Counter( "Manual album art actions: correction_requested, retry_requested, override_deleted", ["action"], ) +art_mbid_lookups_total = Counter( + "scrobbler_art_mbid_lookups_total", + "Album art lookups that tried a scrobble's recording MBID, by result (matched, missed)", + ["result"], +) art_correction_resolutions_total = Counter( "scrobbler_art_correction_resolutions_total", - "Worker outcome of a manual correction, by input (mbid or search) and result", + "Worker outcome of a manual correction, by input (mbid, release_mbid or search) and result", ["input", "result"], ) art_correction_wait_seconds = Histogram( diff --git a/src/scrobbler/migrations/versions/c7d2f08a19e4_user_album_art_release_mbid.py b/src/scrobbler/migrations/versions/c7d2f08a19e4_user_album_art_release_mbid.py new file mode 100644 index 0000000..56fe566 --- /dev/null +++ b/src/scrobbler/migrations/versions/c7d2f08a19e4_user_album_art_release_mbid.py @@ -0,0 +1,25 @@ +"""user album art release mbid + +Revision ID: c7d2f08a19e4 +Revises: a41c9e2d7b53 +Create Date: 2026-10-06 23:10:00.000000 + +""" + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = "c7d2f08a19e4" +down_revision = "a41c9e2d7b53" +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column("user_album_art", sa.Column("release_mbid", sa.String(length=36), nullable=True)) + + +def downgrade(): + op.drop_column("user_album_art", "release_mbid") diff --git a/src/scrobbler/models.py b/src/scrobbler/models.py index d01a102..b9a4670 100644 --- a/src/scrobbler/models.py +++ b/src/scrobbler/models.py @@ -205,6 +205,7 @@ class UserAlbumArt(db.Model): search_artist: Mapped[str | None] = mapped_column(Text) # correction inputs search_album: Mapped[str | None] = mapped_column(Text) release_group_mbid: Mapped[str | None] = mapped_column(String(36)) + release_mbid: Mapped[str | None] = mapped_column(String(36)) # alternative to the group ID content_type: Mapped[str | None] = mapped_column(String(32)) # set iff status == "found" error_code: Mapped[str | None] = mapped_column(String(64)) # set iff status == "error" created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) diff --git a/src/scrobbler/schemas/__init__.py b/src/scrobbler/schemas/__init__.py index 390c35e..693ee80 100644 --- a/src/scrobbler/schemas/__init__.py +++ b/src/scrobbler/schemas/__init__.py @@ -176,11 +176,22 @@ class AlbumArtCorrectionSchema(AlbumArtArgsSchema): release_group_mbid = fields.UUID( metadata={"description": "A MusicBrainz release-group ID; skips the search"} ) + release_mbid = fields.UUID( + metadata={ + "description": "A MusicBrainz release ID, as an alternative to a release-group ID; " + "skips the search" + } + ) @validates_schema def _needs_a_correction(self, data, **kwargs): - if not any(k in data for k in ("search_artist", "search_album", "release_group_mbid")): - raise ValidationError("Give a search_artist, search_album or release_group_mbid") + ids = ("release_group_mbid", "release_mbid") + if not any(k in data for k in ("search_artist", "search_album", *ids)): + raise ValidationError( + "Give a search_artist, search_album, release_group_mbid or release_mbid" + ) + if all(k in data for k in ids): + raise ValidationError("Give a release_group_mbid or a release_mbid, not both") class AlbumArtOverrideSchema(Schema): @@ -190,6 +201,7 @@ class AlbumArtOverrideSchema(Schema): search_artist = fields.String(allow_none=True) search_album = fields.String(allow_none=True) release_group_mbid = fields.String(allow_none=True) + release_mbid = fields.String(allow_none=True) class AlbumArtFailureSchema(Schema): diff --git a/src/scrobbler/services/art.py b/src/scrobbler/services/art.py index 2ba9621..856e924 100644 --- a/src/scrobbler/services/art.py +++ b/src/scrobbler/services/art.py @@ -1,5 +1,9 @@ """Album art: MusicBrainz release-group search + Cover Art Archive, both free and keyless. +A scrobble's MBID (the recording) is tried first when we have one for the album: it names +the release-group exactly, where the text search can only guess. Without one, or without a +matching release, the text search is used as before. + Every (artist, album) lookup is cached in `AlbumArt` — a miss or an error is cached too, so repeat requests for an album we can't find art for don't keep hammering the upstream APIs. `lookup()` resolves *where* the art is (and never raises); `fetch_image()` streams the bytes @@ -109,42 +113,77 @@ def _stale(row: AlbumArt) -> bool: return now - row.checked_at > threshold -def _find_release_group(artist: str, album: str) -> str | None: - """A matching release-group's MBID, or None if MusicBrainz has no match.""" +def _musicbrainz_get(path: str, params: dict[str, str], missing_ok: bool = False) -> dict | None: + """GET a MusicBrainz JSON document, retrying server errors and timeouts. With + `missing_ok`, a 404 returns None; other client errors and exhausted retries raise.""" api_url = current_app.config["MUSICBRAINZ_API_URL"] - query = f'releasegroup:"{_escape(album)}" AND artist:"{_escape(artist)}"' - params = urllib.parse.urlencode({"query": query, "fmt": "json", "limit": "5"}) + query = urllib.parse.urlencode({**params, "fmt": "json"}) retries = current_app.config["MUSICBRAINZ_RETRIES"] for attempt in range(retries + 1): - request = _throttled_request(f"{api_url}release-group/?{params}") + request = _throttled_request(f"{api_url}{path}?{query}") try: with ( _upstream_call("musicbrainz"), urllib.request.urlopen(request, timeout=10) as response, ): - body = json.load(response) + return json.load(response) except urllib.error.HTTPError as err: + if missing_ok and err.code == 404: + return None if attempt == retries or err.code < 500: raise except (urllib.error.URLError, TimeoutError): if attempt == retries: raise - else: - groups = body.get("release-groups") or [] - return groups[0]["id"] if groups else None time.sleep(min(10, 2**attempt)) raise TimeoutError("MusicBrainz request exhausted its retries") -def _cover_art_url(release_group_mbid: str) -> str | None: - """The release-group's front cover URL, or None if Cover Art Archive has none. +def _find_release_group(artist: str, album: str) -> str | None: + """A matching release-group's MBID, or None if MusicBrainz has no match.""" + query = f'releasegroup:"{_escape(album)}" AND artist:"{_escape(artist)}"' + body = _musicbrainz_get("release-group/", {"query": query, "limit": "5"}) or {} + groups = body.get("release-groups") or [] + return groups[0]["id"] if groups else None + + +def _release_group_of_recording(recording_mbid: str, album: str) -> str | None: + """The release-group of the recording's release titled `album`, or None if MusicBrainz + doesn't know the recording or none of its releases has that title.""" + body = _musicbrainz_get( + f"recording/{recording_mbid}", {"inc": "releases+release-groups"}, missing_ok=True + ) + for release in (body or {}).get("releases") or []: + group = release.get("release-group") or {} + if (release.get("title") or "").casefold() == album.casefold() and group.get("id"): + return group["id"] + return None + + +def _scrobbled_recording_mbid(artist: str, album: str) -> str | None: + """A recording MBID some scrobble of this album carried (the newest), if any.""" + return db.session.scalar( + select(Scrobble.mbid) + .where( + func.lower(Scrobble.artist) == artist.lower(), + func.lower(Scrobble.album) == album.lower(), + Scrobble.mbid.is_not(None), + ) + .order_by(Scrobble.played_at.desc()) + .limit(1) + ) + + +def _cover_art_url(mbid: str, entity: str = "release-group") -> str | None: + """The release-group's (or release's) front cover URL, or None if Cover Art Archive + has none. Cover Art Archive redirects to archive.org for the actual image, which is occasionally slow — retried the same way as the MusicBrainz search, with a longer per-attempt timeout to give that redirect room. """ coverart_url = current_app.config["COVERART_API_URL"] - url = f"{coverart_url}release-group/{release_group_mbid}/front-500" + url = f"{coverart_url}{entity}/{mbid}/front-500" retries = current_app.config["MUSICBRAINZ_RETRIES"] for attempt in range(retries + 1): request = urllib.request.Request(url, method="HEAD") @@ -173,12 +212,19 @@ def get_cached(artist: str, album: str) -> AlbumArt | None: ) -def _resolve(artist: str, album: str) -> tuple[ArtResult, str | None, str | None]: +def _resolve( + artist: str, album: str, use_scrobble_mbid: bool = True +) -> tuple[ArtResult, str | None, str | None]: """Live MusicBrainz + Cover Art Archive resolution, no caching involved. Returns (result, release_group_mbid, error_code). Never raises.""" release_group_mbid = None try: - release_group_mbid = _find_release_group(artist, album) + if use_scrobble_mbid and (recording := _scrobbled_recording_mbid(artist, album)): + release_group_mbid = _release_group_of_recording(recording, album) + outcome = "matched" if release_group_mbid else "missed" + metrics.art_mbid_lookups_total.labels(outcome).inc() + if release_group_mbid is None: + release_group_mbid = _find_release_group(artist, album) image_url = _cover_art_url(release_group_mbid) if release_group_mbid else None status = "found" if image_url else "not_found" return ArtResult(status, image_url), release_group_mbid, None @@ -357,9 +403,10 @@ def request_correction( search_artist: str | None, search_album: str | None, release_group_mbid: str | None, + release_mbid: str | None = None, ) -> None: """Queue a corrected lookup (different search text, or a known MusicBrainz - release-group) for the worker. A fast, network-free write.""" + release-group or release) for the worker. A fast, network-free write.""" _upsert_override( user_id, artist, @@ -370,6 +417,7 @@ def request_correction( search_artist=search_artist, search_album=search_album, release_group_mbid=release_group_mbid, + release_mbid=release_mbid, error_code=None, ) metrics.art_override_actions_total.labels("correction_requested").inc() @@ -465,6 +513,7 @@ def list_failures(user_id: int, page: int, limit: int) -> tuple[list[dict], int] "search_artist": override.search_artist, "search_album": override.search_album, "release_group_mbid": override.release_group_mbid, + "release_mbid": override.release_mbid, } if override else None @@ -518,15 +567,20 @@ def _claim_correction() -> UserAlbumArt | None: def _resolve_correction(row: UserAlbumArt) -> tuple[ArtResult, str | None]: - """Live resolution of a user's correction: a known release-group goes straight to - Cover Art Archive, otherwise the (corrected) text is searched. Never raises.""" - if not row.release_group_mbid: + """Live resolution of a user's correction: a known release-group or release goes + straight to Cover Art Archive, otherwise the (corrected) text is searched. Never raises.""" + if not (row.release_group_mbid or row.release_mbid): result, _, error_code = _resolve( - row.search_artist or row.artist, row.search_album or row.album + row.search_artist or row.artist, + row.search_album or row.album, + use_scrobble_mbid=False, # the user gave different text: don't second-guess it ) return result, error_code try: - image_url = _cover_art_url(row.release_group_mbid) + if row.release_mbid: + image_url = _cover_art_url(row.release_mbid, "release") + else: + image_url = _cover_art_url(row.release_group_mbid) except Exception as err: # noqa: BLE001 - any upstream failure is recorded on the row log.warning("Corrected art lookup failed for %r/%r: %s", row.artist, row.album, err) return ArtResult("error"), type(err).__name__ @@ -540,7 +594,7 @@ def resolve_one_correction() -> bool: if row is None: return False start = time.perf_counter() - source = "mbid" if row.release_group_mbid else "search" + source = "release_mbid" if row.release_mbid else "mbid" if row.release_group_mbid else "search" result, error_code = _resolve_correction(row) content_type = None if result.status == "found": diff --git a/tests/test_art.py b/tests/test_art.py index b4b3d3d..1b7e749 100644 --- a/tests/test_art.py +++ b/tests/test_art.py @@ -25,6 +25,18 @@ _RELEASE_GROUPS = { } +# Canned recordings (a scrobble's MBID) and the releases MusicBrainz lists them on. +RECORDING_MBID = "22222222-2222-2222-2222-222222222222" +UNMATCHED_RECORDING_MBID = "33333333-3333-3333-3333-333333333333" +_RECORDINGS = { + RECORDING_MBID: [ + {"title": "Some Compilation", "release-group": {"id": "rg-other"}}, + {"title": "Mbid Album", "release-group": {"id": "rg-found"}}, + ], + UNMATCHED_RECORDING_MBID: [{"title": "Another Album", "release-group": {"id": "rg-other"}}], +} + + def _fake_musicbrainz_caa(environ, start_response): method, path = environ["REQUEST_METHOD"], environ["PATH_INFO"] @@ -41,7 +53,23 @@ def _fake_musicbrainz_caa(environ, start_response): ) return [body] - if path in ("/release-group/rg-found/front-500", f"/release-group/{FOUND_MBID}/front-500"): + if path.startswith("/recording/"): + recording = path.rsplit("/", 1)[1] + releases = _RECORDINGS.get(recording) + if releases is None: + start_response("404 Not Found", [("Content-Type", "text/plain")]) + return [b"not found"] + body = json.dumps({"releases": releases}).encode() + start_response( + "200 OK", [("Content-Type", "application/json"), ("Content-Length", str(len(body)))] + ) + return [body] + + if path in ( + "/release-group/rg-found/front-500", + f"/release-group/{FOUND_MBID}/front-500", + f"/release/{FOUND_MBID}/front-500", + ): body = b"\xff\xd8\xff\xe0fake-jpeg-bytes" headers = [("Content-Type", "image/jpeg"), ("Content-Length", str(len(body)))] start_response("200 OK", headers) @@ -746,3 +774,79 @@ def test_failures_endpoint(client, auth, art_config, user): def test_failures_requires_auth(client): assert client.get("/api/v1/art/failures").status_code == 401 + + +def scrobble_with_mbid(user, artist, track, album, mbid): + scrobbles.submit_scrobbles( + user, None, [TrackInput(artist, track, album=album, mbid=mbid, timestamp=int(time.time()))] + ) + + +def test_scrobble_mbid_finds_the_release_group_without_a_text_match(art_config, user, metric_delta): + # "Mbid Album" matches nothing in the fake's text search, so only the recording can find it + matched = metric_delta("scrobbler_art_mbid_lookups_total", result="matched") + scrobble_with_mbid(user, "Radiohead", "Track", "Mbid Album", RECORDING_MBID) + art.want("Radiohead", "Mbid Album") + assert art.resolve_one_pending() is True + found = row("Radiohead", "Mbid Album") + assert (found.status, found.release_group_mbid) == ("found", "rg-found") + assert matched.delta == 1 + + +def test_scrobble_mbid_with_no_matching_release_falls_back_to_text_search( + art_config, user, metric_delta +): + missed = metric_delta("scrobbler_art_mbid_lookups_total", result="missed") + scrobble_with_mbid(user, "Radiohead", "Track", "In Rainbows", UNMATCHED_RECORDING_MBID) + art.want("Radiohead", "In Rainbows") + art.resolve_one_pending() + assert row("Radiohead", "In Rainbows").release_group_mbid == "rg-found" + assert missed.delta == 1 + + +def test_unknown_scrobble_mbid_falls_back_to_text_search(art_config, user): + unknown = "44444444-4444-4444-4444-444444444444" + scrobble_with_mbid(user, "Radiohead", "Track", "In Rainbows", unknown) + art.want("Radiohead", "In Rainbows") + art.resolve_one_pending() + assert row("Radiohead", "In Rainbows").status == "found" + + +def test_no_scrobble_mbid_means_no_recording_lookup(art_config, user, metric_delta): + tried = metric_delta("scrobbler_art_mbid_lookups_total", result="missed") + scrobble_with_mbid(user, "Radiohead", "Track", "In Rainbows", None) + art.want("Radiohead", "In Rainbows") + art.resolve_one_pending() + assert row("Radiohead", "In Rainbows").status == "found" + assert tried.delta == 0 + + +def test_correction_with_search_text_ignores_the_scrobble_mbid(art_config, user): + scrobble_with_mbid(user, "Radiohead", "Track", "Mbid Album", RECORDING_MBID) + art.request_correction(user.id, "Radiohead", "Mbid Album", None, "No Art Album", None) + art.resolve_one_pending() + assert override(user, "Radiohead", "Mbid Album").status == "error" # searched the text given + + +def test_correction_by_release_mbid_is_resolved_from_the_release(art_config, user, metric_delta): + resolved = metric_delta( + "scrobbler_art_correction_resolutions_total", input="release_mbid", result="found" + ) + art.request_correction(user.id, "Radiohead", "Inrainbows", None, None, None, FOUND_MBID) + assert art.resolve_one_pending() is True + fixed = override(user, "Radiohead", "Inrainbows") + assert (fixed.status, fixed.release_mbid) == ("found", FOUND_MBID) + assert art.read_override_file(fixed) == b"\xff\xd8\xff\xe0fake-jpeg-bytes" + assert resolved.delta == 1 + + +def test_correction_api_accepts_a_release_mbid_but_not_both_ids(client, auth): + url = "/api/v1/art/album/correction" + ok = {"artist": "A", "album": "B", "release_mbid": FOUND_MBID} + response = client.put(url, headers=auth, json=ok) + assert response.status_code == 202 + assert response.get_json()["release_mbid"] == FOUND_MBID + both = {**ok, "release_group_mbid": FOUND_MBID} + assert client.put(url, headers=auth, json=both).status_code == 422 + bad = {"artist": "A", "album": "B", "release_mbid": "nope"} + assert client.put(url, headers=auth, json=bad).status_code == 422