sonda/internal/naming/naming.go
tgiachi a880b87a9e chore: move the module path to git.kmalloc.org/squid/sonda
Migrating hosting from Codeberg to git.kmalloc.org. Renames the
module path in go.mod, every internal import, and the OCI image
source label in the Dockerfile. Build and full test suite verified
green after the rename.
2026-11-15 17:30:29 +01:00

336 lines
11 KiB
Go

// Package naming makes a name and a line of description for a list of songs: a playlist, a mix, a smart playlist.
//
// It is a pipeline over the facts about the list (its few main genres and artists, how many songs, a few words about
// the rules, the language wanted), and it never needs anybody: a local namer builds a name from the facts on this
// server, and nothing leaves it. When an admin turned the Claude provider on (see package anthropic), Claude is asked
// first; what it answers is kept, so the same facts are not asked twice, and when it fails or declines the local name
// is given. A name is a suggestion: nothing here changes a playlist.
package naming
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"slices"
"sort"
"strings"
"time"
"unicode"
"go.uber.org/zap"
"git.kmalloc.org/squid/sonda/internal/catalog"
"git.kmalloc.org/squid/sonda/internal/mixes"
"git.kmalloc.org/squid/sonda/internal/providers"
"git.kmalloc.org/squid/sonda/internal/providers/anthropic"
)
// Where a suggestion came from.
const (
SourceClaude = "claude"
SourceLocal = "local"
)
// Facts are what is known of a list of songs. Genres and Artists have the commonest first.
type Facts struct {
Kind string // "playlist", "mix" or "smart"
Genres []string
Artists []string
Tracks int
Hint string // the rules of a smart playlist, in a few words
}
// Suggestion is a name, a line of description and where they came from.
type Suggestion struct {
Name string
Description string
Source string
}
// Settings says whether the Claude provider can be used now, and gives its key: *providers.Service.
type Settings interface {
Active(ctx context.Context, name string) (providers.Settings, bool, error)
}
// Claude asks the Claude API for a name: *anthropic.Client.
type Claude interface {
Name(ctx context.Context, key string, req anthropic.Request) (anthropic.Result, error)
}
// Store keeps the names Claude gave and reads what the songs are about.
type Store interface {
Get(ctx context.Context, key string) (Suggestion, bool, error)
Put(ctx context.Context, key string, s Suggestion, now time.Time) error
// GenreCounts returns, for the songs, how many of them have each genre, as the files spell it.
GenreCounts(ctx context.Context, trackIDs []int64) (map[string]int, error)
}
// How a call to Claude ended, and why it failed.
const (
OutcomeMade = "made" // Claude made a name
OutcomeKept = "kept" // the name was one that Claude had made before, taken from the kept ones: nothing was billed
OutcomeFailed = "failed" // Claude gave no name
ReasonNoName = "no_name" // it declined, was cut short or did not answer with a name
ReasonKey = "key"
ReasonRate = "rate"
ReasonUnreachable = "unreachable"
ReasonOther = "other"
)
// Call is one question to Claude, for the account of what it costs. It holds nothing of the facts that were sent: no
// artist, no genre, no name.
type Call struct {
At time.Time
Kind string // "playlist", "mix" or "smart"
Model string
Outcome string
Reason string // for a failure
Usage anthropic.Usage
}
// Meter keeps the account of the calls.
type Meter interface {
Record(ctx context.Context, c Call) error
}
// Service makes the suggestions.
type Service struct {
settings Settings
claude Claude
store Store
meter Meter
ledger Ledger
log *zap.Logger
now func() time.Time
}
// SetMeter makes the service record every question it asks Claude. Call it before the service is used.
func (s *Service) SetMeter(m Meter) { s.meter = m }
// record keeps a call; the account never stops a name.
func (s *Service) record(ctx context.Context, c Call) {
if s.meter == nil {
return
}
c.At, c.Model = s.now(), anthropic.Model
if err := s.meter.Record(ctx, c); err != nil {
s.log.Warn("a call to Claude could not be recorded", zap.Error(err))
}
}
// reasonOf says why a call failed, in one word.
func reasonOf(err error) string {
switch {
case errors.Is(err, anthropic.ErrNoName):
return ReasonNoName
case errors.Is(err, providers.ErrKeyRefused):
return ReasonKey
case errors.Is(err, providers.ErrRateLimited):
return ReasonRate
case errors.Is(err, providers.ErrUnreachable):
return ReasonUnreachable
}
return ReasonOther
}
// NewService builds a Service. log may be nil.
func NewService(settings Settings, claude Claude, store Store, log *zap.Logger) *Service {
if log == nil {
log = zap.NewNop()
}
return &Service{settings: settings, claude: claude, store: store, log: log, now: time.Now}
}
// lang is the language code as it is used: "en" or "it", English for anything else.
func lang(code string) string {
code = strings.ToLower(strings.TrimSpace(code))
if i := strings.IndexAny(code, "-_"); i >= 0 {
code = code[:i]
}
if code == "it" {
return "it"
}
return "en"
}
// limit cuts the facts to what is sent and compared.
func limit(f Facts) Facts {
f.Genres = slices.Clone(f.Genres)
f.Artists = slices.Clone(f.Artists)
if len(f.Genres) > anthropic.MaxGenres {
f.Genres = f.Genres[:anthropic.MaxGenres]
}
if len(f.Artists) > anthropic.MaxArtists {
f.Artists = f.Artists[:anthropic.MaxArtists]
}
if r := []rune(f.Hint); len(r) > anthropic.MaxHintLen {
f.Hint = string(r[:anthropic.MaxHintLen])
}
return f
}
// cacheKey identifies a question: the same facts in the same language to the same model. The number of songs is
// not in it, so a playlist that gains a song keeps its name.
func cacheKey(f Facts, language string) string {
h := sha256.New()
fmt.Fprintf(h, "%s\x00%s\x00%s\x00%s\x00%s\x00%s", anthropic.Model, language, f.Kind, strings.Join(f.Genres, "\x01"), strings.Join(f.Artists, "\x01"), f.Hint)
return hex.EncodeToString(h.Sum(nil))
}
// Suggest gives a name for the facts, in the language (a code like "en" or "it"): Claude's when the provider is on and
// it answered, the local one otherwise. It does not fail because a provider does.
func (s *Service) Suggest(ctx context.Context, f Facts, language string) (Suggestion, error) {
language = lang(language)
f = limit(f)
if len(f.Genres) == 0 && len(f.Artists) == 0 {
return local(f, language), nil // nothing to say about it, to Claude either
}
set, on, err := s.settings.Active(ctx, providers.Anthropic)
if err != nil {
s.log.Warn("the Claude provider could not be read", zap.Error(err))
return local(f, language), nil
}
if !on {
return local(f, language), nil
}
key := cacheKey(f, language)
if got, ok, err := s.store.Get(ctx, key); err != nil {
s.log.Warn("a kept name could not be read", zap.Error(err))
} else if ok {
s.record(ctx, Call{Kind: f.Kind, Outcome: OutcomeKept})
return got, nil
}
res, err := s.claude.Name(ctx, set.APIKey, anthropic.Request{
Kind: f.Kind, Genres: f.Genres, Artists: f.Artists, Tracks: f.Tracks, Hint: f.Hint, Language: language,
})
if err != nil {
s.log.Warn("Claude gave no name", zap.String("provider", providers.Anthropic), zap.Error(err))
s.record(ctx, Call{Kind: f.Kind, Outcome: OutcomeFailed, Reason: reasonOf(err), Usage: res.Usage})
return local(f, language), nil
}
s.record(ctx, Call{Kind: f.Kind, Outcome: OutcomeMade, Usage: res.Usage})
out := Suggestion{Name: res.Name, Description: res.Description, Source: SourceClaude}
if err := s.store.Put(ctx, key, out, s.now()); err != nil {
s.log.Warn("a name could not be kept", zap.Error(err))
}
return out, nil
}
// Auto says whether names are made by themselves: the Claude provider is on, with its key. A provider that cannot be
// read counts as off.
func (s *Service) Auto(ctx context.Context) bool {
_, on, err := s.settings.Active(ctx, providers.Anthropic)
return err == nil && on
}
// junkArtists are the names that stand for nobody.
var junkArtists = map[string]bool{"unknown artist": true, "various artists": true, "": true}
// FactsOf works the facts out of a list of songs: the artists and the genres they have the most, the commonest first and
// by name among equals. The names that stand for nobody ("Unknown Artist") and the tags that are no genre are left out,
// and the spellings the files have of a genre are one.
func (s *Service) FactsOf(ctx context.Context, kind string, tracks []catalog.Track, hint string) (Facts, error) {
f := Facts{Kind: kind, Tracks: len(tracks), Hint: hint}
if len(tracks) == 0 {
return f, nil
}
artists := map[string]int{}
ids := make([]int64, len(tracks))
for i, t := range tracks {
ids[i] = t.ID
seen := map[string]bool{}
for _, a := range t.Artists {
name := strings.TrimSpace(a.Name)
if junkArtists[strings.ToLower(name)] || seen[name] {
continue
}
seen[name] = true
artists[name]++
}
}
raw, err := s.store.GenreCounts(ctx, ids)
if err != nil {
return Facts{}, fmt.Errorf("count genres: %w", err)
}
genres := map[string]int{}
for g, n := range raw {
if norm := mixes.NormalizeGenre(g); norm != "" {
genres[norm] += n
}
}
f.Artists, f.Genres = commonest(artists), commonest(genres)
return f, nil
}
// commonest lists the keys, the one with the biggest count first and by name among equals.
func commonest(counts map[string]int) []string {
out := make([]string, 0, len(counts))
for k := range counts {
out = append(out, k)
}
sort.Slice(out, func(i, j int) bool {
if counts[out[i]] != counts[out[j]] {
return counts[out[i]] > counts[out[j]]
}
return out[i] < out[j]
})
return out
}
// ---- the local namer ----
func titleCase(s string) string {
words := strings.Fields(s)
for i, w := range words {
r := []rune(w)
r[0] = unicode.ToUpper(r[0])
words[i] = string(r)
}
return strings.Join(words, " ")
}
// local builds a name from the facts, with nothing from anybody.
func local(f Facts, language string) Suggestion {
it := language == "it"
say := func(en, itText string) string {
if it {
return itText
}
return en
}
var name string
switch {
case len(f.Genres) > 0 && f.Kind == "mix":
g := titleCase(f.Genres[0])
name = say(g+" Mix", "Mix "+g)
case len(f.Genres) > 1:
name = titleCase(f.Genres[0]) + " & " + titleCase(f.Genres[1])
case len(f.Genres) == 1:
name = titleCase(f.Genres[0])
case len(f.Artists) == 1:
name = f.Artists[0]
case len(f.Artists) == 2:
name = f.Artists[0] + " & " + f.Artists[1]
case len(f.Artists) > 2:
name = f.Artists[0] + ", " + f.Artists[1] + say(" & more", " e altri")
default:
name = say("New playlist", "Nuova playlist")
}
var desc string
if n := len(f.Artists); n > 0 {
shown := f.Artists[:min(n, 3)]
desc = say("With ", "Con ") + strings.Join(shown, ", ")
if n > 3 {
desc += say(" and more", " e altri")
}
desc += "."
} else if f.Tracks == 1 {
desc = say("1 song.", "1 brano.")
} else {
desc = fmt.Sprintf(say("%d songs.", "%d brani."), f.Tracks)
}
return Suggestion{Name: name, Description: desc, Source: SourceLocal}
}