sonda/internal/taste/service.go
tgiachi ca5cbbf088 feat: favourites teach Sonda my taste
A heart adds to what the listening says of an artist: a favourite artist counts
as much as three complete listens, a favourite album 1.5 for its album artist and
a favourite song 1 for each of its main artists, at most 6 for one artist, without
fading with time. An artist hearted but never played is liked, with no listens.
That feeds Discover, the mixes and the smart playlists that use the taste, and
GET /me/taste.

In the mixes of what the listener likes (genre mixes, Your favourites,
Rediscover) a hearted song is wanted 1.5 times as much and a song on a hearted
album 1.25 times. New to you is not changed.
2026-11-16 11:08:20 +01:00

176 lines
5.5 KiB
Go

package taste
import (
"context"
"errors"
"fmt"
"sort"
"time"
)
// ErrInvalidQuery is returned for a limit that makes no sense.
var ErrInvalidQuery = errors.New("invalid query")
// Limits of the artist list.
const (
DefaultLimit = 20
MaxLimit = 50
// MaxTags is how many tags the profile keeps, the best first.
MaxTags = 50
// MaxProfileArtists is how many of the liked artists, the most liked first,
// shape the tag profile. The rest weigh too little to change it and cost a read each.
MaxProfileArtists = 200
// lookbackHalfLives is how far back the history is read: an event ten
// half-lives old weighs less than a thousandth of a new one.
lookbackHalfLives = 10
defaultHalfLife = 90 * 24 * time.Hour
)
// Store reads what the model needs. It never writes.
type Store interface {
// ArtistEvents returns the listener's events since the given time, one per
// credited artist of the track. Events of deleted tracks are gone with them.
ArtistEvents(ctx context.Context, userID int64, since time.Time) ([]Event, error)
// ArtistTags returns, per artist, the tags already stored for it with weights
// from 0 to 1 (genres of the files and tags that providers gave). It reads
// the database only.
ArtistTags(ctx context.Context, artistIDs []int64) (map[int64]map[string]float64, error)
// ArtistFavorites returns, per artist, the hearts of the listener that point at it.
ArtistFavorites(ctx context.Context, userID int64) (map[int64]Favorites, error)
// ArtistNames returns the names of the given artists.
ArtistNames(ctx context.Context, artistIDs []int64) (map[int64]string, error)
}
// ArtistTaste is an artist the listener likes.
type ArtistTaste struct {
ID int64
Name string
Preference float64 // above 0, at most 1
Listens int
LastListened time.Time
}
// Profile is what Sonda has learned about a listener.
type Profile struct {
Artists []ArtistTaste // liked artists, the most liked first
Tags []TagWeight // best first, the top one is 1
}
// Service works out profiles.
type Service struct {
store Store
opts Options
now func() time.Time
}
// NewService builds a Service.
func NewService(store Store, o Options) *Service {
if o.HalfLife <= 0 {
o.HalfLife = defaultHalfLife // a zero would make every weight NaN
}
return &Service{store: store, opts: o, now: time.Now}
}
// Learned is everything the model knows about a listener, for other parts of
// Sonda to build on.
type Learned struct {
Prefs map[int64]ArtistPref // every artist with events, the avoided ones too
Liked []ArtistPref // the ones with a positive score, the most played first
Tags []TagWeight // the tag profile of the liked artists, best first, not cut
}
// Learn works out what the listener's history says, and what their favourites say: each heart adds to the artist it
// points at (see FavoriteValue). Artists are ordered by how much
// the listener played them, recent plays counting more; ties go to the lower id. The
// tag profile is built from the MaxProfileArtists most played liked artists.
func (s *Service) Learn(ctx context.Context, userID int64) (Learned, error) {
now := s.now()
events, err := s.store.ArtistEvents(ctx, userID, now.Add(-lookbackHalfLives*s.opts.HalfLife))
if err != nil {
return Learned{}, fmt.Errorf("read events: %w", err)
}
favs, err := s.store.ArtistFavorites(ctx, userID)
if err != nil {
return Learned{}, fmt.Errorf("read favourites: %w", err)
}
out := Learned{Prefs: WithFavorites(Preferences(events, now, s.opts), favs), Liked: []ArtistPref{}, Tags: []TagWeight{}}
for _, p := range out.Prefs {
if p.Score > 0 {
out.Liked = append(out.Liked, p)
}
}
sort.Slice(out.Liked, func(i, j int) bool {
a, b := out.Liked[i], out.Liked[j]
if a.Score != b.Score {
return a.Score > b.Score
}
return a.ArtistID < b.ArtistID
})
if len(out.Liked) == 0 {
return out, nil
}
top := out.Liked
if len(top) > MaxProfileArtists {
top = top[:MaxProfileArtists]
}
ids := make([]int64, len(top))
prefs := make(map[int64]ArtistPref, len(top))
for i, p := range top {
ids[i], prefs[p.ArtistID] = p.ArtistID, p
}
tags, err := s.store.ArtistTags(ctx, ids)
if err != nil {
return Learned{}, fmt.Errorf("read tags: %w", err)
}
out.Tags = TagProfile(prefs, tags)
return out, nil
}
// Taste returns the listener's profile: up to limit liked artists (zero means
// DefaultLimit) and the best MaxTags tags of the profile built from the liked artists.
func (s *Service) Taste(ctx context.Context, userID int64, limit int) (Profile, error) {
if limit < 0 {
return Profile{}, fmt.Errorf("%w: limit cannot be negative", ErrInvalidQuery)
}
switch {
case limit == 0:
limit = DefaultLimit
case limit > MaxLimit:
limit = MaxLimit
}
l, err := s.Learn(ctx, userID)
if err != nil {
return Profile{}, err
}
profile := Profile{Artists: []ArtistTaste{}, Tags: l.Tags}
if len(profile.Tags) > MaxTags {
profile.Tags = profile.Tags[:MaxTags]
}
if len(l.Liked) == 0 {
return profile, nil
}
shown := l.Liked
if len(shown) > limit {
shown = shown[:limit]
}
shownIDs := make([]int64, len(shown))
for i, p := range shown {
shownIDs[i] = p.ArtistID
}
names, err := s.store.ArtistNames(ctx, shownIDs)
if err != nil {
return Profile{}, fmt.Errorf("read names: %w", err)
}
for _, p := range shown {
profile.Artists = append(profile.Artists, ArtistTaste{
ID: p.ArtistID, Name: names[p.ArtistID], Preference: p.Preference,
Listens: p.Listens, LastListened: p.LastListened,
})
}
return profile, nil
}