Add artist recommendation CLI with Qobuz downloads
This commit is contained in:
4 files changed
+270
No files matched your search
@@ -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...)
|
||||
}
|
||||
Reference in new issue
Block a user