from difflib import SequenceMatcher from lyra_worker.types import Candidate, MBTarget def _sim(a: str, b: str) -> float: return SequenceMatcher(None, a.strip().casefold(), b.strip().casefold()).ratio() def score_confidence(target: MBTarget, c: Candidate) -> float: """0..1 confidence that candidate c is the requested target.""" artist_sim = _sim(target.artist, c.matched_artist) album_sim = _sim(target.album, c.matched_album) if target.track_count is None or target.track_count == c.track_count: track_factor = 1.0 else: diff = abs(target.track_count - c.track_count) track_factor = max(0.0, 1.0 - diff / max(target.track_count, 1)) return 0.5 * artist_sim + 0.4 * album_sim + 0.1 * track_factor