443 lines
11 KiB
Go
443 lines
11 KiB
Go
// Package matcher matches Apple Music albums to Qobuz albums. It tries UPC
|
|
// first, then a fuzzy artist/title search, and verifies fuzzy candidates by
|
|
// comparing the ISRCs of the playlist tracks against the Qobuz track list.
|
|
package matcher
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"applesync/internal/model"
|
|
"applesync/internal/state"
|
|
"applesync/internal/text"
|
|
)
|
|
|
|
type QobuzClient interface {
|
|
SearchAlbums(ctx context.Context, query string, limit int) ([]model.QobuzAlbum, error)
|
|
GetAlbum(ctx context.Context, albumID string) (*model.QobuzAlbum, error)
|
|
}
|
|
|
|
type Matcher struct {
|
|
client QobuzClient
|
|
cache *state.MatchCache
|
|
concurrency int
|
|
refresh bool
|
|
logf func(string, ...any)
|
|
}
|
|
|
|
func New(client QobuzClient, cache *state.MatchCache, concurrency int) *Matcher {
|
|
if concurrency < 1 {
|
|
concurrency = 1
|
|
}
|
|
return &Matcher{client: client, cache: cache, concurrency: concurrency}
|
|
}
|
|
|
|
func (m *Matcher) SetLogf(fn func(string, ...any)) { m.logf = fn }
|
|
|
|
// SetRefresh makes the matcher ignore existing cache entries (including
|
|
// negative ones) for this run. New results are still cached.
|
|
func (m *Matcher) SetRefresh(refresh bool) { m.refresh = refresh }
|
|
|
|
func (m *Matcher) log(format string, args ...any) {
|
|
if m.logf != nil {
|
|
m.logf(format, args...)
|
|
}
|
|
}
|
|
|
|
// MatchAll matches every album concurrently. Albums that cannot be matched are
|
|
// absent from the map; their reasons are cached and logged.
|
|
func (m *Matcher) MatchAll(ctx context.Context, albums []*model.Album) (map[string]*model.AlbumMatch, error) {
|
|
matches := make(map[string]*model.AlbumMatch, len(albums))
|
|
var mu sync.Mutex
|
|
var done atomic.Int64
|
|
total := len(albums)
|
|
|
|
sem := make(chan struct{}, m.concurrency)
|
|
var wg sync.WaitGroup
|
|
for _, album := range albums {
|
|
wg.Add(1)
|
|
go func(album *model.Album) {
|
|
defer wg.Done()
|
|
select {
|
|
case sem <- struct{}{}:
|
|
defer func() { <-sem }()
|
|
case <-ctx.Done():
|
|
return
|
|
}
|
|
match, err := m.matchOne(ctx, album)
|
|
n := done.Add(1)
|
|
if err != nil {
|
|
m.log("qobuz: [%d/%d] %s — %s: error: %v", n, total, album.Artist, album.Title, err)
|
|
return
|
|
}
|
|
if match != nil {
|
|
mu.Lock()
|
|
matches[album.AppleID] = match
|
|
mu.Unlock()
|
|
m.log("qobuz: [%d/%d] %s — %s -> %s [%s]", n, total, album.Artist, album.Title, match.QobuzAlbumID, match.Method)
|
|
return
|
|
}
|
|
m.log("qobuz: [%d/%d] %s — %s: no match", n, total, album.Artist, album.Title)
|
|
}(album)
|
|
}
|
|
wg.Wait()
|
|
if err := ctx.Err(); err != nil {
|
|
return matches, err
|
|
}
|
|
return matches, nil
|
|
}
|
|
|
|
func (m *Matcher) matchOne(ctx context.Context, album *model.Album) (*model.AlbumMatch, error) {
|
|
if album.AppleID == "" {
|
|
return nil, fmt.Errorf("album has no Apple id")
|
|
}
|
|
if m.cache != nil && !m.refresh {
|
|
if entry, ok := m.cache.Get(album.AppleID); ok {
|
|
if entry.Match != nil {
|
|
match := *entry.Match
|
|
if match.AppleAlbumID == "" {
|
|
match.AppleAlbumID = album.AppleID
|
|
}
|
|
return &match, nil
|
|
}
|
|
if entry.Error != "" {
|
|
m.log("qobuz: cached miss for %s — %s: %s", album.Artist, album.Title, entry.Error)
|
|
return nil, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
match, reason, err := m.lookup(ctx, album)
|
|
now := time.Now()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if match != nil {
|
|
match.AppleAlbumID = album.AppleID
|
|
match.CheckedAt = now
|
|
if m.cache != nil {
|
|
m.cache.Put(album.AppleID, model.CachedMatch{Match: match, CheckedAt: now})
|
|
}
|
|
return match, nil
|
|
}
|
|
if m.cache != nil {
|
|
m.cache.Put(album.AppleID, model.CachedMatch{Error: reason, CheckedAt: now})
|
|
}
|
|
return nil, nil
|
|
}
|
|
|
|
func (m *Matcher) lookup(ctx context.Context, album *model.Album) (*model.AlbumMatch, string, error) {
|
|
upc := normalizeUPC(album.UPC)
|
|
if upc != "" {
|
|
for _, variant := range upcVariants(album.UPC) {
|
|
candidates, err := m.client.SearchAlbums(ctx, variant, 10)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
var exact []model.QobuzAlbum
|
|
for _, candidate := range candidates {
|
|
if normalizeUPC(candidate.UPC) == upc {
|
|
exact = append(exact, candidate)
|
|
}
|
|
}
|
|
if len(exact) > 0 {
|
|
sort.SliceStable(exact, func(i, j int) bool {
|
|
return score(album, exact[i]) > score(album, exact[j])
|
|
})
|
|
best := exact[0]
|
|
// Enrich the match when possible; a failure here does not
|
|
// invalidate an exact UPC match.
|
|
_ = verify(ctx, m.client, album, &best)
|
|
return toMatch(&best, "upc", 1.0), "", nil
|
|
}
|
|
}
|
|
}
|
|
|
|
cleanTitle := text.SearchTitle(album.Title)
|
|
queries := uniqueQueries(
|
|
strings.TrimSpace(album.Artist+" "+cleanTitle),
|
|
strings.TrimSpace(cleanTitle+" "+album.Artist),
|
|
cleanTitle,
|
|
)
|
|
seen := map[string]bool{}
|
|
var candidates []model.QobuzAlbum
|
|
for _, query := range queries {
|
|
if query == "" {
|
|
continue
|
|
}
|
|
found, err := m.client.SearchAlbums(ctx, query, 10)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
for _, candidate := range found {
|
|
if candidate.ID == "" || seen[candidate.ID] {
|
|
continue
|
|
}
|
|
seen[candidate.ID] = true
|
|
candidates = append(candidates, candidate)
|
|
}
|
|
}
|
|
type scored struct {
|
|
album model.QobuzAlbum
|
|
score float64
|
|
}
|
|
ranked := make([]scored, 0, len(candidates))
|
|
for _, candidate := range candidates {
|
|
s := score(album, candidate)
|
|
if text.Similarity(candidate.Title, cleanTitle) < 0.85 {
|
|
continue
|
|
}
|
|
if album.Artist != "" && text.Similarity(candidate.Artist, album.Artist) < 0.60 {
|
|
continue
|
|
}
|
|
ranked = append(ranked, scored{album: candidate, score: s})
|
|
}
|
|
sort.SliceStable(ranked, func(i, j int) bool { return ranked[i].score > ranked[j].score })
|
|
if len(ranked) == 0 || ranked[0].score < 0.72 {
|
|
return nil, "no Qobuz search match", nil
|
|
}
|
|
|
|
maxVerify := 3
|
|
for i := 0; i < len(ranked) && i < maxVerify; i++ {
|
|
candidate := ranked[i].album
|
|
full, err := m.client.GetAlbum(ctx, candidate.ID)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if full.TrackCount > 0 {
|
|
candidate.TrackCount = full.TrackCount
|
|
}
|
|
if full.Title != "" {
|
|
candidate.Title = full.Title
|
|
}
|
|
if full.Artist != "" {
|
|
candidate.Artist = full.Artist
|
|
}
|
|
method := verifyISRCs(album, full)
|
|
if method != "" {
|
|
conf := ranked[i].score
|
|
if method == "isrc" {
|
|
conf = maxFloat(conf, 0.95)
|
|
}
|
|
return toMatch(&candidate, method, conf), "", nil
|
|
}
|
|
// A very strong metadata match can be accepted even when Qobuz has no
|
|
// ISRC tags, as long as the track count also agrees.
|
|
if len(full.Tracks) > 0 && countISRCs(full) == 0 && ranked[i].score >= 0.92 && trackCountEqual(album, full) {
|
|
return toMatch(&candidate, "fuzzy", ranked[i].score), "", nil
|
|
}
|
|
}
|
|
return nil, "Qobuz candidates did not verify", nil
|
|
}
|
|
|
|
func verify(ctx context.Context, client QobuzClient, album *model.Album, candidate *model.QobuzAlbum) error {
|
|
full, err := client.GetAlbum(ctx, candidate.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if full.TrackCount > 0 {
|
|
candidate.TrackCount = full.TrackCount
|
|
}
|
|
if candidate.Title == "" {
|
|
candidate.Title = full.Title
|
|
}
|
|
if candidate.Artist == "" {
|
|
candidate.Artist = full.Artist
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// verifyISRCs returns "isrc" if enough of the playlist track ISRCs are present
|
|
// on the Qobuz album, "fuzzy" if the metadata is strong but ISRCs are missing,
|
|
// and "" if the candidate should be rejected.
|
|
func verifyISRCs(album *model.Album, qalbum *model.QobuzAlbum) string {
|
|
appleISRCs := make(map[string]bool)
|
|
for _, track := range album.Tracks {
|
|
if track.ISRC != "" {
|
|
appleISRCs[track.ISRC] = true
|
|
}
|
|
}
|
|
qISRCs := make(map[string]bool)
|
|
for _, track := range qalbum.Tracks {
|
|
if track.ISRC != "" {
|
|
qISRCs[track.ISRC] = true
|
|
}
|
|
}
|
|
overlap := 0
|
|
for isrc := range appleISRCs {
|
|
if qISRCs[isrc] {
|
|
overlap++
|
|
}
|
|
}
|
|
// Qobuz and Apple sometimes carry different editions of the same album:
|
|
// identical artist, title, year and track count but different UPCs and a
|
|
// shifted ISRC block. Treat that as a strong match rather than rejecting it.
|
|
strong := metadataStrong(album, qalbum)
|
|
if len(appleISRCs) == 0 {
|
|
if strong {
|
|
return "fuzzy"
|
|
}
|
|
return ""
|
|
}
|
|
if overlap == 0 {
|
|
if strong {
|
|
return "fuzzy"
|
|
}
|
|
return ""
|
|
}
|
|
if overlap == len(appleISRCs) {
|
|
return "isrc"
|
|
}
|
|
if overlap >= 1 {
|
|
// Even a partial ISRC overlap is strong evidence when the release
|
|
// metadata agrees; Qobuz may only carry a shorter edition than Apple.
|
|
// If the playlist uses more than one track from this album, the Qobuz
|
|
// edition must at least be large enough to contain them.
|
|
playlistTracks := len(album.Tracks)
|
|
if playlistTracks == 0 {
|
|
playlistTracks = len(appleISRCs)
|
|
}
|
|
if qalbum.TrackCount > 0 && qalbum.TrackCount < playlistTracks && overlap < len(appleISRCs) {
|
|
return ""
|
|
}
|
|
titleSim := text.Similarity(qalbum.Title, text.SearchTitle(album.Title))
|
|
artistSim := text.Similarity(qalbum.Artist, album.Artist)
|
|
if titleSim >= 0.90 && artistSim >= 0.85 {
|
|
return "isrc"
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func metadataStrong(album *model.Album, qalbum *model.QobuzAlbum) bool {
|
|
if !trackCountEqual(album, qalbum) {
|
|
return false
|
|
}
|
|
titleSim := text.Similarity(qalbum.Title, text.SearchTitle(album.Title))
|
|
artistSim := text.Similarity(qalbum.Artist, album.Artist)
|
|
if titleSim < 0.95 || artistSim < 0.85 {
|
|
return false
|
|
}
|
|
if album.Year > 0 && qalbum.Year > 0 {
|
|
diff := album.Year - qalbum.Year
|
|
if diff < 0 {
|
|
diff = -diff
|
|
}
|
|
if diff > 1 {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func countISRCs(album *model.QobuzAlbum) int {
|
|
n := 0
|
|
for _, track := range album.Tracks {
|
|
if track.ISRC != "" {
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
func trackCountEqual(a *model.Album, b *model.QobuzAlbum) bool {
|
|
return a.TrackCount > 0 && b.TrackCount > 0 && a.TrackCount == b.TrackCount
|
|
}
|
|
|
|
func score(album *model.Album, candidate model.QobuzAlbum) float64 {
|
|
titleSim := text.Similarity(candidate.Title, text.SearchTitle(album.Title))
|
|
artistSim := text.Similarity(candidate.Artist, album.Artist)
|
|
s := 0.55*titleSim + 0.30*artistSim
|
|
if album.TrackCount > 0 && candidate.TrackCount > 0 {
|
|
if album.TrackCount == candidate.TrackCount {
|
|
s += 0.10
|
|
} else {
|
|
s -= 0.10
|
|
}
|
|
}
|
|
if album.Year > 0 && candidate.Year > 0 {
|
|
diff := album.Year - candidate.Year
|
|
if diff < 0 {
|
|
diff = -diff
|
|
}
|
|
switch {
|
|
case diff <= 1:
|
|
s += 0.05
|
|
case diff > 3:
|
|
s -= 0.05
|
|
}
|
|
}
|
|
if text.IsNoisyAlbum(candidate.Title) {
|
|
s -= 0.15
|
|
}
|
|
return s
|
|
}
|
|
|
|
func toMatch(candidate *model.QobuzAlbum, method string, confidence float64) *model.AlbumMatch {
|
|
return &model.AlbumMatch{
|
|
QobuzAlbumID: candidate.ID,
|
|
QobuzTitle: candidate.Title,
|
|
QobuzArtist: candidate.Artist,
|
|
QobuzUPC: candidate.UPC,
|
|
QobuzTrackCount: candidate.TrackCount,
|
|
Method: method,
|
|
Confidence: confidence,
|
|
}
|
|
}
|
|
|
|
func normalizeUPC(value string) string {
|
|
var b strings.Builder
|
|
for _, r := range value {
|
|
if r >= '0' && r <= '9' {
|
|
b.WriteRune(r)
|
|
}
|
|
}
|
|
return strings.TrimLeft(b.String(), "0")
|
|
}
|
|
|
|
func upcVariants(value string) []string {
|
|
digits := normalizeUPC(value)
|
|
if digits == "" {
|
|
return nil
|
|
}
|
|
variants := []string{digits}
|
|
if len(digits) < 13 {
|
|
variants = append([]string{strings.Repeat("0", 13-len(digits)) + digits}, variants...)
|
|
}
|
|
seen := map[string]bool{}
|
|
out := make([]string, 0, len(variants))
|
|
for _, v := range variants {
|
|
if v != "" && !seen[v] {
|
|
seen[v] = true
|
|
out = append(out, v)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func uniqueQueries(values ...string) []string {
|
|
seen := map[string]bool{}
|
|
out := make([]string, 0, len(values))
|
|
for _, value := range values {
|
|
value = strings.TrimSpace(value)
|
|
if value == "" || seen[value] {
|
|
continue
|
|
}
|
|
seen[value] = true
|
|
out = append(out, value)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func maxFloat(a, b float64) float64 {
|
|
if a > b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|