from __future__ import annotations import difflib import re import unicodedata _PARENS = re.compile(r"\([^)]*\)|\[[^\]]*\]") _FEAT = re.compile(r"\b(feat\.?|ft\.?|featuring|with)\b.*$", re.IGNORECASE) _NON_WORD = re.compile(r"[^\w]+", re.UNICODE) def normalize(value: str) -> str: """Normalize artist/title strings while preserving non-Latin scripts.""" if not value: return "" text = unicodedata.normalize("NFKC", value).casefold() text = _PARENS.sub(" ", text) text = _FEAT.sub(" ", text) text = _NON_WORD.sub(" ", text) return " ".join(text.split()) def track_key(artist: str, title: str) -> str: return f"{normalize(artist)}::{normalize(title)}" def similarity(left: str, right: str) -> float: if not left or not right: return 0.0 return difflib.SequenceMatcher(None, left, right).ratio() def best_match(items: list[dict], artist: str, title: str) -> dict | None: """Find the closest song in a small Navidrome search result.""" want_artist = normalize(artist) want_title = normalize(title) best = None best_score = 0.0 for item in items: got_artist = normalize(item.get("artist") or "") got_title = normalize(item.get("title") or "") if not got_artist or not got_title: continue if got_artist == want_artist and got_title == want_title: return item title_score = similarity(got_title, want_title) artist_score = similarity(got_artist, want_artist) score = title_score * 0.65 + artist_score * 0.35 if score > best_score: best_score = score best = item if best and best_score >= 0.86: return best return None def human_duration(seconds: int | float | None) -> str: if not seconds: return "" seconds = int(seconds) return f"{seconds // 60}:{seconds % 60:02d}"