Commit 9a65fa5a authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Rank identify_audio candidates by confidence, not source order

Shazam's hit was always appended before AcoustID's, so every caller
(discovery_listen, _identify_tag_and_store) taking candidates[0] as
"the" match was really just picking "whichever source responded
first" - a lower-confidence Shazam hit would silently beat a
higher-scoring AcoustID one from the same batch. Now sorted by
confidence descending before returning, fixing ranking for Discovery,
Upload, and Telegram tagging at once since they all share this one
function.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 34fe74d2
Pipeline #1155 failed with stage
in 39 minutes and 5 seconds
......@@ -92,6 +92,11 @@ async def identify_audio(file_path: str) -> list:
except Exception as e:
logger.error(f"AcoustID error: {e}")
# Highest-confidence match first - callers all just take candidates[0] as "the" match, so
# without this a Shazam hit (appended first, always) would win even when an AcoustID
# candidate from the very same batch scored higher. `or 0` is defensive, not reachable
# today: every candidate this function itself builds always sets a real confidence value.
candidates.sort(key=lambda c: c.get('confidence') or 0, reverse=True)
return candidates
async def identify_with_gemini(file_path: str, lang_pref: str) -> dict:
......
import asyncio
from src.services.music_identification import fetch_lyrics, parse_lrc
from src.services.music_identification import fetch_lyrics, identify_audio, parse_lrc
def test_parse_lrc_basic_lines():
......@@ -86,3 +86,51 @@ def test_fetch_lyrics_synced_search_error_falls_back_to_plain(mocker):
result = asyncio.run(fetch_lyrics("Song", "Artist"))
assert result == {"lyrics": "plain lyrics only", "synced_lyrics": None}
assert search.call_count == 2
def _mock_shazam_hit(mocker, title="Shazam Title", artist="Shazam Artist"):
shazam_instance = mocker.Mock()
shazam_instance.recognize = mocker.AsyncMock(
return_value={"track": {"title": title, "subtitle": artist, "images": {}, "sections": []}}
)
mocker.patch("src.services.music_identification.Shazam", return_value=shazam_instance)
mocker.patch(
"src.services.music_identification.musicbrainzngs.get_recording_by_id",
return_value={"recording": {"release-list": []}},
)
def test_identify_audio_ranks_by_confidence_not_source_order(mocker):
"""Regression: Shazam is always appended to the candidates list first (if it returns a hit
at all), regardless of its confidence relative to AcoustID's real match score - every
caller (discovery_listen, _identify_tag_and_store) just takes candidates[0] as "the" match,
so without sorting, a lower-confidence Shazam hit would win over a genuinely
higher-confidence AcoustID one from the very same batch."""
_mock_shazam_hit(mocker)
mocker.patch(
"src.services.music_identification.acoustid.match",
return_value=[(0.99, "rec-id-1", "AcoustID Title", "AcoustID Artist")],
)
candidates = asyncio.run(identify_audio("/tmp/does-not-matter.mp3"))
assert len(candidates) == 2
assert candidates[0]["source"] == "AcoustID"
assert candidates[0]["confidence"] == 99.0
assert candidates[1]["source"] == "Shazam"
assert candidates[1]["confidence"] == 95.0
def test_identify_audio_keeps_shazam_first_when_it_genuinely_has_higher_confidence(mocker):
_mock_shazam_hit(mocker)
mocker.patch(
"src.services.music_identification.acoustid.match",
return_value=[(0.5, "rec-id-2", "Low Confidence Title", "Low Confidence Artist")],
)
candidates = asyncio.run(identify_audio("/tmp/does-not-matter.mp3"))
assert candidates[0]["source"] == "Shazam"
assert candidates[0]["confidence"] == 95.0
assert candidates[1]["source"] == "AcoustID"
assert candidates[1]["confidence"] == 50.0
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