Commit 73e00a51 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Fetch cover art from Cover Art Archive for AcoustID matches

AcoustID/MusicBrainz identify the recording but never carry artwork,
so every AcoustID-sourced match showed no cover art at all even when
Shazam-matched songs had one. Cover Art Archive (keyed by the same
release MBID MusicBrainz already gives us) is the standard companion
source - HEAD-checked before use so a release with nothing archived
falls back to the existing null-coverart UI state instead of a broken
image.
parent 91450d45
Pipeline #1289 failed with stage
import asyncio
import re
import acoustid
import aiohttp
import musicbrainzngs
import syncedlyrics
from shazamio import Shazam
......@@ -13,6 +14,22 @@ if GEMINI_API_KEY:
musicbrainzngs.set_useragent("StaxBot", "0.1", "contact@example.com")
async def _fetch_cover_art_archive_url(release_id: str) -> str | None:
"""AcoustID/MusicBrainz identify a recording, not artwork - Cover Art Archive (run by the
Internet Archive, keyed by the same release MBID) is the standard companion source for the
actual image. A HEAD check first (rather than just handing back the URL unconditionally)
because a release with no art archived 404s with no redirect - storing that URL anyway would
show a broken-image icon in the UI instead of the existing null-coverart fallback."""
url = f"https://coverartarchive.org/release/{release_id}/front-500"
try:
async with aiohttp.ClientSession() as session:
async with session.head(url, allow_redirects=True, timeout=aiohttp.ClientTimeout(total=5)) as response:
return url if response.status == 200 else None
except Exception as e:
logger.error(f"Cover Art Archive lookup failed for release {release_id}: {e}")
return None
async def compute_fingerprint(file_path: str) -> str | None:
"""Local Chromaprint fingerprint of the audio content - no network call. Used as the
cache key so re-uploads of the same song skip identification entirely. Returns None if
......@@ -70,7 +87,7 @@ async def identify_audio(file_path: str) -> list:
for score, recording_id, title, artist in results:
if score > 0.4:
if not any(c['title'].lower() == title.lower() and c['artist'].lower() == artist.lower() for c in candidates):
album, year, genre, track_number = "Unknown Album", "Unknown Year", "Unknown Genre", "1/1"
album, year, genre, track_number, coverart = "Unknown Album", "Unknown Year", "Unknown Genre", "1/1", None
try:
mb_data = await asyncio.to_thread(musicbrainzngs.get_recording_by_id, recording_id, includes=["releases"])
rec = mb_data.get('recording', {})
......@@ -80,12 +97,14 @@ async def identify_audio(file_path: str) -> list:
album = rel.get('title', album)
year = rel.get('date', year)[:4] if rel.get('date') else year
track_number = f"{rel.get('medium-list', [{}])[0].get('track-list', [{}])[0].get('number', '1')}/{rel.get('medium-list', [{}])[0].get('track-count', '1')}"
if rel.get('id'):
coverart = await _fetch_cover_art_archive_url(rel['id'])
except Exception as e:
logger.error(f"MusicBrainz release lookup failed for recording {recording_id}: {e}")
candidates.append({
'title': title, 'artist': artist, 'album': album, 'year': year, 'genre': genre,
'track_number': track_number, 'source': 'AcoustID', 'coverart': None, 'lyrics': None,
'track_number': track_number, 'source': 'AcoustID', 'coverart': coverart, 'lyrics': None,
'confidence': round(score * 100, 1),
})
if len(candidates) >= 4: break
......
......@@ -134,3 +134,53 @@ def test_identify_audio_keeps_shazam_first_when_it_genuinely_has_higher_confiden
assert candidates[0]["confidence"] == 95.0
assert candidates[1]["source"] == "AcoustID"
assert candidates[1]["confidence"] == 50.0
def test_identify_audio_fetches_cover_art_archive_for_acoustid_match(mocker):
"""AcoustID/MusicBrainz identify the recording but never carry artwork - Cover Art Archive
(keyed by the release MBID) is the real image source. Regression: this used to be hardcoded
to None unconditionally, so every AcoustID-only match showed no cover art at all even when
the release genuinely has one archived."""
shazam_instance = mocker.Mock()
shazam_instance.recognize = mocker.AsyncMock(return_value={})
mocker.patch("src.services.music_identification.Shazam", return_value=shazam_instance)
mocker.patch(
"src.services.music_identification.acoustid.match",
return_value=[(0.95, "rec-id-1", "House in the Woods", "Low Roar")],
)
mocker.patch(
"src.services.music_identification.musicbrainzngs.get_recording_by_id",
return_value={"recording": {"release-list": [{"id": "release-mbid-1", "title": "House in the Woods"}]}},
)
fetch_cover_art = mocker.patch(
"src.services.music_identification._fetch_cover_art_archive_url",
new=mocker.AsyncMock(return_value="https://coverartarchive.org/release/release-mbid-1/front-500"),
)
candidates = asyncio.run(identify_audio("/tmp/does-not-matter.mp3"))
assert len(candidates) == 1
assert candidates[0]["coverart"] == "https://coverartarchive.org/release/release-mbid-1/front-500"
fetch_cover_art.assert_called_once_with("release-mbid-1")
def test_identify_audio_leaves_coverart_null_when_archive_has_none(mocker):
shazam_instance = mocker.Mock()
shazam_instance.recognize = mocker.AsyncMock(return_value={})
mocker.patch("src.services.music_identification.Shazam", return_value=shazam_instance)
mocker.patch(
"src.services.music_identification.acoustid.match",
return_value=[(0.95, "rec-id-1", "Obscure Title", "Obscure Artist")],
)
mocker.patch(
"src.services.music_identification.musicbrainzngs.get_recording_by_id",
return_value={"recording": {"release-list": [{"id": "release-mbid-2", "title": "Obscure Title"}]}},
)
mocker.patch(
"src.services.music_identification._fetch_cover_art_archive_url",
new=mocker.AsyncMock(return_value=None),
)
candidates = asyncio.run(identify_audio("/tmp/does-not-matter.mp3"))
assert candidates[0]["coverart"] is None
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment