From 1d3a35069bed0dd73a669c0811923d0e24e34d99 Mon Sep 17 00:00:00 2001 From: Joren Date: Fri, 27 Nov 2026 14:51:56 +0100 Subject: [PATCH] Add artist recommendation CLI with Qobuz downloads --- lastrecc-go/README.md | 5 + lastrecc-go/cmd/lastrecc/main.go | 215 ++++++++++++++++++++++++++ lastrecc-go/cmd/lastrecc/main_test.go | 31 ++++ lastrecc-go/internal/config/config.go | 19 +++ 4 files changed, 270 insertions(+) create mode 100644 lastrecc-go/cmd/lastrecc/main_test.go diff --git a/lastrecc-go/README.md b/lastrecc-go/README.md index fad69d4..2d1ea64 100644 --- a/lastrecc-go/README.md +++ b/lastrecc-go/README.md @@ -94,6 +94,11 @@ go build -o lastrecc ./cmd/lastrecc ./lastrecc plan --json # machine-readable plan ./lastrecc weekly # download missing albums + rebuild playlist ./lastrecc weekly --dry-run # same as plan + +./lastrecc artist "Кино" --limit 10 # similar artists + a top album each +./lastrecc artist "Кино" --download --dry-run # show Qobuz matches +./lastrecc artist "Кино" --download # fetch the top albums +./lastrecc artist "Cher" --json # machine-readable ``` Useful limits while experimenting: diff --git a/lastrecc-go/cmd/lastrecc/main.go b/lastrecc-go/cmd/lastrecc/main.go index d053263..72bcbb6 100644 --- a/lastrecc-go/cmd/lastrecc/main.go +++ b/lastrecc-go/cmd/lastrecc/main.go @@ -7,6 +7,7 @@ import ( "fmt" "os" "path/filepath" + "strconv" "strings" "time" @@ -15,6 +16,7 @@ import ( "lastrecc-go/internal/lastfm" "lastrecc-go/internal/navidrome" "lastrecc-go/internal/rip" + "lastrecc-go/internal/text" ) type cliFlags struct { @@ -51,6 +53,8 @@ func main() { os.Exit(runPlan(os.Args[2:])) case "seeds": os.Exit(runSeeds(os.Args[2:])) + case "artist": + os.Exit(runArtist(os.Args[2:])) case "help", "-h", "--help": usage() case "version": @@ -69,6 +73,8 @@ Usage: lastrecc weekly [flags] build the weekly playlist and fetch missing albums lastrecc plan [flags] dry-run: show seeds, albums and Qobuz hits lastrecc seeds [flags] show the weighted listening seeds + lastrecc artist NAME recommend similar artists for one artist + lastrecc artist NAME --download [--dry-run] lastrecc version Options are passed after the command. Common flags: @@ -228,6 +234,176 @@ func buildClients(cfg *config.Config, logf func(string, ...any)) *clients { } } +func runArtist(args []string) int { + fs := flag.NewFlagSet("artist", flag.ContinueOnError) + env := fs.String("env", "", "env file") + limit := fs.Int("limit", 10, "number of similar artists") + stateDir := fs.String("state-dir", "", "cache directory") + noAlbums := fs.Bool("no-albums", false, "skip top-album lookups") + asJSON := fs.Bool("json", false, "print JSON") + download := fs.Bool("download", false, "download the selected top albums via streamrip-go") + dryRun := fs.Bool("dry-run", false, "with --download, only show Qobuz matches") + if err := fs.Parse(reorderFlags(args)); err != nil { + return 2 + } + if fs.NArg() < 1 { + fmt.Fprintln(os.Stderr, "usage: lastrecc artist NAME [--limit N] [--no-albums] [--json] [--download [--dry-run]]") + return 2 + } + query := strings.Join(fs.Args(), " ") + if *limit < 1 { + *limit = 10 + } + if *limit > 50 { + *limit = 50 + } + key, _, err := config.LoadLastFMOnly(*env) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + dir := *stateDir + if dir == "" { + dir = os.Getenv("STATE_DIR") + } + if dir == "" { + dir = "state" + } + cacheDir := filepath.Join(dir, "cache") + if err := os.MkdirAll(cacheDir, 0o755); err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + fm := lastfm.New(key, cacheDir) + ctx := context.Background() + similar, err := fm.SimilarArtists(ctx, query, *limit) + if err != nil { + fmt.Fprintln(os.Stderr, "artist:", err) + return 1 + } + type recommendation struct { + Name string `json:"name"` + Match float64 `json:"match"` + URL string `json:"url,omitempty"` + Album string `json:"album,omitempty"` + AlbumPlays int `json:"album_playcount,omitempty"` + } + results := make([]recommendation, 0, len(similar)) + for _, artist := range similar { + item := recommendation{ + Name: artist.Name, + Match: float64(artist.Match), + URL: artist.URL, + } + if !*noAlbums { + albums, err := fm.ArtistTopAlbums(ctx, artist.Name, 5) + if err == nil { + for _, album := range albums { + if album.Name == "" || text.IsNoisyAlbum(album.Name) { + continue + } + item.Album = album.Name + item.AlbumPlays = int(album.Playcount) + break + } + } + } + results = append(results, item) + } + if *asJSON { + payload := struct { + Artist string `json:"artist"` + Similar []recommendation `json:"similar"` + }{Artist: query, Similar: results} + data, _ := json.MarshalIndent(payload, "", " ") + fmt.Println(string(data)) + } else if len(results) == 0 { + fmt.Printf("No similar artists found for %q.\n", query) + } else { + fmt.Printf("Recommendations for %s\n\n", query) + for i, item := range results { + album := "" + if item.Album != "" { + album = " · " + item.Album + } + fmt.Printf("%2d. %-32s %3.0f%%%s\n", i+1, fit(item.Name, 32), item.Match*100, album) + } + } + + if *download { + if *noAlbums { + fmt.Fprintln(os.Stderr, "cannot combine --download with --no-albums") + return 2 + } + ripBinary := os.Getenv("RIP_BINARY") + if ripBinary == "" { + ripBinary = config.DefaultRipBinary() + } + quality := -1 + if value := os.Getenv("QUALITY"); value != "" { + if parsed, err := strconv.Atoi(value); err == nil { + quality = parsed + } + } + searchDelay := 800 * time.Millisecond + if value := os.Getenv("SEARCH_DELAY_MS"); value != "" { + if parsed, err := strconv.Atoi(value); err == nil && parsed > 0 { + searchDelay = time.Duration(parsed) * time.Millisecond + } + } + runner := &rip.Runner{ + Binary: ripBinary, + ConfigPath: os.Getenv("RIP_CONFIG"), + Quality: quality, + SearchDelay: searchDelay, + StateDir: dir, + Logf: func(format string, args ...any) { + fmt.Fprintf(os.Stderr, "[artist] "+format+"\n", args...) + }, + } + if !runner.Available() { + fmt.Fprintf(os.Stderr, "streamrip binary not found: %s\n", ripBinary) + return 1 + } + var hits []rip.Hit + seen := map[string]bool{} + for _, item := range results { + if item.Album == "" { + continue + } + fmt.Fprintf(os.Stderr, "[artist] Qobuz lookup: %s — %s\n", item.Name, item.Album) + hit, err := runner.SearchAlbum(ctx, item.Name, item.Album) + if err != nil { + fmt.Fprintf(os.Stderr, "[artist] %s: %v\n", item.Name, err) + continue + } + if hit == nil { + fmt.Fprintf(os.Stderr, "[artist] %s — %s: no Qobuz match\n", item.Name, item.Album) + continue + } + if seen[hit.ID] { + continue + } + seen[hit.ID] = true + hits = append(hits, *hit) + fmt.Fprintf(os.Stderr, "[artist] Qobuz: %s (%s, %.0f%%)\n", hit.Title, hit.ID, hit.Score*100) + } + if len(hits) == 0 { + fmt.Fprintln(os.Stderr, "no albums matched on Qobuz") + } else if *dryRun { + fmt.Fprintf(os.Stderr, "Would download %d album(s).\n", len(hits)) + } else { + fmt.Fprintf(os.Stderr, "Downloading %d album(s) through streamrip-go...\n", len(hits)) + if err := runner.DownloadAlbums(ctx, hits); err != nil { + fmt.Fprintln(os.Stderr, "download:", err) + return 1 + } + fmt.Fprintf(os.Stderr, "Downloaded %d album(s).\n", len(hits)) + } + } + return 0 +} + func runSeeds(args []string) int { fs := flag.NewFlagSet("seeds", flag.ContinueOnError) f := bindFlags(fs) @@ -441,3 +617,42 @@ func acquireLock(stateDir string) (func(), error) { _ = f.Close() return func() { _ = os.Remove(path) }, nil } + +func fit(value string, width int) string { + runes := []rune(value) + if len(runes) <= width { + return value + } + if width <= 1 { + return string(runes[:width]) + } + return string(runes[:width-1]) + "…" +} + +// reorderFlags lets `artist NAME --limit 5` work with the standard flag +// package, which normally stops parsing at the first positional argument. +func reorderFlags(args []string) []string { + valueFlags := map[string]bool{ + "-limit": true, "--limit": true, + "-env": true, "--env": true, + "-state-dir": true, "--state-dir": true, + } + var flags, positional []string + for i := 0; i < len(args); i++ { + arg := args[i] + if arg == "--" { + positional = append(positional, args[i+1:]...) + break + } + if !strings.HasPrefix(arg, "-") || arg == "-" { + positional = append(positional, arg) + continue + } + flags = append(flags, arg) + if !strings.Contains(arg, "=") && valueFlags[arg] && i+1 < len(args) { + i++ + flags = append(flags, args[i]) + } + } + return append(flags, positional...) +} diff --git a/lastrecc-go/cmd/lastrecc/main_test.go b/lastrecc-go/cmd/lastrecc/main_test.go new file mode 100644 index 0000000..6dcba51 --- /dev/null +++ b/lastrecc-go/cmd/lastrecc/main_test.go @@ -0,0 +1,31 @@ +package main + +import ( + "reflect" + "testing" +) + +func TestReorderFlagsMovesValueFlagsBeforeArtist(t *testing.T) { + got := reorderFlags([]string{"Кино", "--limit", "5", "--json"}) + want := []string{"--limit", "5", "--json", "Кино"} + if !reflect.DeepEqual(got, want) { + t.Fatalf("reorderFlags() = %#v, want %#v", got, want) + } +} + +func TestReorderFlagsEqualsForm(t *testing.T) { + got := reorderFlags([]string{"Кино", "--limit=5", "--no-albums"}) + want := []string{"--limit=5", "--no-albums", "Кино"} + if !reflect.DeepEqual(got, want) { + t.Fatalf("reorderFlags() = %#v, want %#v", got, want) + } +} + +func TestFit(t *testing.T) { + if got := fit("Кино", 10); got != "Кино" { + t.Fatalf("fit() = %q", got) + } + if got := fit("Nautilus Pompilius", 10); got != "Nautilus …" { + t.Fatalf("fit() = %q", got) + } +} diff --git a/lastrecc-go/internal/config/config.go b/lastrecc-go/internal/config/config.go index 1447cda..464dd1e 100644 --- a/lastrecc-go/internal/config/config.go +++ b/lastrecc-go/internal/config/config.go @@ -102,6 +102,21 @@ func Load(envPath string, getenv func(string) string) (*Config, error) { return cfg, nil } +// LoadLastFMOnly is for standalone commands that only need the Last.fm key. +func LoadLastFMOnly(envPath string) (string, string, error) { + path := findEnv(envPath) + if path != "" { + if err := loadDotEnv(path); err != nil { + return "", path, err + } + } + key := strings.TrimSpace(os.Getenv("LASTFM_API_KEY")) + if key == "" { + return "", path, fmt.Errorf("missing LASTFM_API_KEY (looked at %s)", path) + } + return key, path, nil +} + func (c *Config) Validate() error { var missing []string if c.NavidromeURL == "" { @@ -173,6 +188,10 @@ func loadDotEnv(path string) error { return scanner.Err() } +func DefaultRipBinary() string { + return defaultRipBinary() +} + func defaultRipBinary() string { // Prefer a bundled Go `rip` next to this binary, then the local clone. // A Python streamrip `rip` may also be on PATH and has a different