From f546ef4d5de2e0877b5990cca1c781c8fc096ad6 Mon Sep 17 00:00:00 2001 From: Junaid Irfan Date: Tue, 24 Nov 2026 01:35:07 -0500 Subject: [PATCH 1/2] For You: suggestions from what you play, worked out locally MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Every song played for 30 s goes in a local log (~/.local/share/trill/plays). Seeds are the songs you play, each play counting half as much every 14 days; your newest liked songs fill in while the log is short. - Candidates: the radio of the top 4 seed songs, and the top songs of artists Spotify lists as related to your top 4 artists (the artist-page query trill already sends for play counts). Fetched in parallel, about 2 s. - Ranked locally: liked songs and "not interested" are left out, songs played a lot in the last 30 days are pushed down, and each further song by an artist counts half (3 at most). The Why column says where each one came from. - Opening it shows the last list from disk at once; it's worked out again after 12 h, or on R. - X on a For You song, or a ✦ smart-shuffle song, marks it not interested (kept in ~/.local/share/trill/not_interested); a playing ✦ song is skipped. Smart shuffle leaves them out too. - Fix: opening a list while another was still loading let the slow one replace it when it arrived. - The startup frame lists the same sidebar entries as the real one, so nothing jumps. --- src/api.rs | 69 ++++++++-- src/app.rs | 75 +++++++++- src/app/extras.rs | 40 +++++- src/discover.rs | 342 ++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 4 + src/ui.rs | 8 +- 6 files changed, 519 insertions(+), 19 deletions(-) create mode 100644 src/discover.rs diff --git a/src/api.rs b/src/api.rs index a880ffb..2d8629b 100644 --- a/src/api.rs +++ b/src/api.rs @@ -627,14 +627,6 @@ pub async fn track_rows(session: &Session, uris: Vec) -> Res> { /// Songs Spotify recommends for a list (its radio station), for smart shuffle. Seeded by /// the list (playlists, albums, artists), else by `track` (Liked Songs, search). Up to 50. pub async fn recommendations(session: &Session, list: &str, track: &str) -> Vec { - async fn station(session: &Session, seed: &str) -> Vec { - let scope = if seed.starts_with("spotify:track:") { "tracks" } else { "stations" }; - let Ok(body) = session.spclient().get_apollo_station(scope, seed, Some(50), Vec::new(), false).await else { - return Vec::new(); - }; - let v: Value = serde_json::from_slice(&body).unwrap_or_default(); - station_uris(&v) - } let mut uris = if list.starts_with("spotify:") { station(session, list).await } else { Vec::new() }; if uris.is_empty() { uris = station(session, track).await; @@ -642,6 +634,48 @@ pub async fn recommendations(session: &Session, list: &str, track: &str) -> Vec< track_rows(session, uris).await.unwrap_or_default() } +/// Up to 50 songs of Spotify's radio for a list or a song (empty if it has none). +pub async fn station(session: &Session, seed: &str) -> Vec { + let scope = if seed.starts_with("spotify:track:") { "tracks" } else { "stations" }; + let Ok(body) = session.spclient().get_apollo_station(scope, seed, Some(50), Vec::new(), false).await else { + return Vec::new(); + }; + let v: Value = serde_json::from_slice(&body).unwrap_or_default(); + station_uris(&v) +} + +/// Each song's first artist, as (artist uri, name), from one batched metadata request. +pub async fn track_artists(session: &Session, uris: &[String]) -> Res> { + Ok(entities::(session, uris, ExtensionKind::TRACK_V4) + .await? + .into_iter() + .filter_map(|(u, t)| { + let a = t.artist.first()?; + Some((u, (gid_uri("artist", a.gid())?, a.name().to_string()))) + }) + .collect()) +} + +/// What an artist's page lists besides their music: related artists (uri, name), and the +/// uris of their top songs. The same GraphQL query the artist page uses for play counts. +pub async fn artist_overview(session: &Session, uri: &str) -> Res<(Vec<(String, String)>, Vec)> { + let v = gql(session, GQL_ARTIST, serde_json::json!({ "uri": uri, "locale": "", "includePrerelease": false })).await?; + Ok(overview_of(&v["data"]["artistUnion"])) +} + +fn overview_of(a: &Value) -> (Vec<(String, String)>, Vec) { + let items = |v: &Value| v["items"].as_array().cloned().unwrap_or_default(); + let related = items(&a["relatedContent"]["relatedArtists"]) + .iter() + .filter_map(|r| Some((r["uri"].as_str()?.to_string(), r["profile"]["name"].as_str().unwrap_or("").to_string()))) + .collect(); + let top = items(&a["discography"]["topTracks"]) + .iter() + .filter_map(|t| t["track"]["uri"].as_str().filter(|u| u.starts_with("spotify:track:")).map(String::from)) + .collect(); + (related, top) +} + fn station_uris(v: &Value) -> Vec { v["tracks"].as_array().into_iter().flatten().filter_map(|t| t["uri"].as_str()).filter(|u| u.starts_with("spotify:track:")).map(String::from).collect() } @@ -697,6 +731,11 @@ fn list_path(dir: &std::path::Path, uri: &str) -> std::path::PathBuf { dir.join("lists").join(uri.replace([':', '/', '\\'], "_")) } +/// How long ago the list was saved. +pub fn list_age(dir: &std::path::Path, uri: &str) -> Option { + std::fs::metadata(list_path(dir, uri)).and_then(|m| m.modified()).ok()?.elapsed().ok() +} + pub fn read_list_cache(dir: &std::path::Path, uri: &str) -> Option> { let text = std::fs::read_to_string(list_path(dir, uri)).ok()?; let mut lines = text.lines(); @@ -995,6 +1034,20 @@ mod tests { assert!(station_uris(&Value::Null).is_empty()); } + #[test] + fn reads_artist_overview() { + let v: Value = serde_json::from_str(r#"{ + "relatedContent": {"relatedArtists": {"items": [ + {"uri": "spotify:artist:a", "profile": {"name": "Nile Rodgers"}}, {"profile": {"name": "no uri"}}]}}, + "discography": {"topTracks": {"items": [ + {"track": {"uri": "spotify:track:1", "playcount": "5"}}, {"track": {"uri": "spotify:episode:2"}}]}} + }"#).unwrap(); + let (related, top) = overview_of(&v); + assert_eq!(related, [("spotify:artist:a".to_string(), "Nile Rodgers".to_string())]); + assert_eq!(top, ["spotify:track:1"]); + assert_eq!(overview_of(&Value::Null), (Vec::new(), Vec::new())); + } + #[test] fn album_rows_show_year_and_type() { use librespot_protocol::metadata::{Date, album::Type}; diff --git a/src/app.rs b/src/app.rs index 5ad332c..ffb3ca4 100644 --- a/src/app.rs +++ b/src/app.rs @@ -23,6 +23,7 @@ use crate::{ audio::{AudioSettings, BANDS, Eq}, auth::WebToken, engine::{Engine, EngineEvent}, + discover::{self, FOR_YOU}, mpris::Remote, }; @@ -67,8 +68,10 @@ fn weave(order: &mut Vec, from: usize, mut recs: std::ops::Range) } } -/// Sidebar entries above the playlists: Liked Songs, Albums, Artists, Queue, Search. -const FIXED_SIDE: usize = 5; +/// Sidebar entries above the playlists: Liked Songs, Albums, Artists, For You, Queue, Search. +const FIXED_SIDE: usize = 6; +/// For You is worked out again when it's opened this long after the last time (or on `R`). +const FOR_YOU_FRESH: Duration = Duration::from_secs(12 * 3600); #[derive(Clone, Copy, PartialEq, Eq)] pub enum Focus { @@ -198,6 +201,7 @@ fn sorted(sort: Sort, uri: &str, rows: Rows) -> (Rows, Option<&'static str>) { #[derive(Clone, Copy, PartialEq, Eq)] pub enum SideKind { Liked, + ForYou, Queue, Search, Playlist, @@ -274,6 +278,12 @@ pub struct App { pub soloist_missing: Option, /// Where the playlist list is cached so the sidebar fills instantly on start. pub cache_dir: Option, + /// Where settings, the play log and "not interested" live. + pub data_dir: Option, + /// Songs never to suggest again (`X`). + pub not_interested: HashSet, + /// The song whose play is already in the log (it's logged once it has played 30 s). + logged: Option, /// Tag of a newer trill release, shown in the title bar. pub update: Option, /// EQ panel open, with this band selected. @@ -375,6 +385,10 @@ pub struct App { const SEEK_MS: u32 = 10_000; +fn for_you_status(n: usize) -> String { + format!("For You: {n} songs from what you play, worked out here. X: not interested · R: new picks") +} + fn playlists_status(n: usize) -> String { format!("{n} playlists. Tab to switch panes, / to search, ? for keys.") } @@ -398,6 +412,7 @@ impl App { SideItem { name: "♥ Liked Songs".into(), uri: format!("spotify:user:{user}:collection"), kind: SideKind::Liked, editable: false, pinned: false }, SideItem { name: "◉ Albums".into(), uri: api::SAVED_ALBUMS.into(), kind: SideKind::Liked, editable: false, pinned: false }, SideItem { name: "◈ Artists".into(), uri: api::FOLLOWED_ARTISTS.into(), kind: SideKind::Liked, editable: false, pinned: false }, + SideItem { name: "✦ For You".into(), uri: FOR_YOU.into(), kind: SideKind::ForYou, editable: false, pinned: false }, SideItem { name: "≡ Queue".into(), uri: "trill:queue".into(), kind: SideKind::Queue, editable: false, pinned: false }, SideItem { name: "⌕ Search".into(), uri: "trill:search".into(), kind: SideKind::Search, editable: false, pinned: false }, ]; @@ -426,6 +441,9 @@ impl App { eq, eq_allowed: true, cache_dir: None, + data_dir: None, + not_interested: HashSet::new(), + logged: None, update: None, eq_panel: None, help_open: false, @@ -524,7 +542,20 @@ impl App { self.back.remove(0); } } - if !force && let Some(rows) = self.cache.get(&uri).cloned() { + if !force && uri != FOR_YOU && let Some(rows) = self.cache.get(&uri).cloned() { + self.show(uri, title, rows); + return; + } + // For You from disk, as it was last worked out, unless that was a while ago + if !force + && uri == FOR_YOU + && let Some(dir) = self.cache_dir.as_deref() + && api::list_age(dir, &uri).is_some_and(|a| a < FOR_YOU_FRESH) + && let Some(rows) = api::read_list_cache(dir, &uri) + { + let rows: Rows = Arc::new(rows); + self.cache.insert(uri.clone(), rows.clone()); // so `X` can take songs out of it + self.status = for_you_status(rows.len()); self.show(uri, title, rows); return; } @@ -556,6 +587,18 @@ impl App { /// Load a list; `known` rows (an older copy) spare re-fetching their songs' details. fn fetch_rows(&self, uri: String, title: String, known: Rows) { let (s, tx) = (self.session.clone(), self.tx.clone()); + if uri == FOR_YOU { + let Some(dir) = self.data_dir.clone() else { return }; + let liked = self.cache.get(&self.liked_uri()).cloned().or_else(|| { + self.cache_dir.as_deref().and_then(|d| api::read_list_cache(d, &self.liked_uri())).map(Arc::new) + }); + let exclude: HashSet = self.liked.iter().chain(&self.not_interested).cloned().collect(); + tokio::spawn(async move { + let rows = discover::for_you(&s, &dir, liked.unwrap_or_default(), exclude).await; + let _ = tx.send(Msg::Rows { uri, title, rows }); + }); + return; + } tokio::spawn(async move { let rows = api::context_rows(&s, &uri, &known).await; let _ = tx.send(Msg::Rows { uri, title, rows }); @@ -563,6 +606,11 @@ impl App { } fn show(&mut self, uri: String, title: String, rows: Rows) { + // another list still loading mustn't replace this one when it arrives + if self.pending.as_deref() != Some(uri.as_str()) { + self.pending = None; + self.loading = false; + } let (all, sort) = sorted(self.sort_for(&uri), &uri, rows); // a fresh copy of the list on screen keeps what it's narrowed to let find = if self.view.uri == uri { std::mem::take(&mut self.view.find) } else { String::new() }; @@ -669,7 +717,7 @@ impl App { let rows = self.search_rows.clone(); self.show("trill:search".into(), self.search_title.clone(), rows); } - SideKind::Liked | SideKind::Playlist => self.open(uri, name, false, false), + SideKind::Liked | SideKind::Playlist | SideKind::ForYou => self.open(uri, name, false, false), } // Picking "Search" means "I want to search": open the search box right away. self.focus = if kind == SideKind::Search { Focus::Input } else { Focus::Main }; @@ -737,7 +785,7 @@ impl App { crate::trim_heap(); } if is_current { - self.status = format!("{title}: {}", count(&rows)); + self.status = if uri == FOR_YOU { for_you_status(rows.len()) } else { format!("{title}: {}", count(&rows)) }; self.show(uri, title, rows); } else if changed && self.view.uri == uri { // The copy on screen came from disk; this is the fresh one. @@ -1008,6 +1056,20 @@ impl App { /// Seek again while Soloist plays well before the resume point (see `pending_seek`). /// Runs on each position report and each second: after a restart Soloist first sends /// the old session's snapshot, then starts our track from 0 and may report nothing more. + /// Log the song playing once it has played 30 s (again after it starts over), for For You. + pub fn note_play(&mut self) { + let Some(now) = self.now.as_ref() else { return }; + let pos = self.position_ms(); + if pos >= 30_000 && self.logged.as_deref() != Some(now.uri.as_str()) { + if let Some(dir) = self.data_dir.as_deref() { + discover::log_play(dir, now); + } + self.logged = Some(now.uri.clone()); + } else if pos < 5_000 && self.logged.as_deref() == Some(now.uri.as_str()) { + self.logged = None; // repeat one, or played again: counts again after 30 s + } + } + pub fn check_resume(&mut self) { let Some((want, until, last)) = self.pending_seek else { return }; if Instant::now() > until { @@ -1772,6 +1834,7 @@ impl App { self.input = self.view.find.clone(); } KeyCode::Char('z') => self.cycle_sleep(), + KeyCode::Char('X') => self.mark_not_interested(), KeyCode::Char(' ') => self.toggle(), KeyCode::Char('n') => self.next(false), KeyCode::Char('p') => self.prev(), @@ -1820,7 +1883,7 @@ impl App { if self.focus == Focus::Side || self.view.uri.is_empty() { self.status = "Reloading playlists…".into(); self.load_playlists(); - } else if !self.view.uri.starts_with("trill:") || self.view.uri.starts_with("trill:collection:") { + } else if !self.view.uri.starts_with("trill:") || self.view.uri.starts_with("trill:collection:") || self.view.uri == FOR_YOU { let (u, t) = (self.view.uri.clone(), self.view.title.clone()); self.open(u, t, false, true); } diff --git a/src/app/extras.rs b/src/app/extras.rs index ba1d967..23a8af5 100644 --- a/src/app/extras.rs +++ b/src/app/extras.rs @@ -17,6 +17,7 @@ use ratatui_image::{FilterType, Resize, picker::Picker, protocol::Protocol}; use super::{App, Focus, Msg, SideKind}; use crate::{ api::{self, Kind, Row}, + discover::{self, FOR_YOU}, library::{self, Lyrics}, theme, }; @@ -484,6 +485,40 @@ impl App { }); } + /// `X` on a For You song or a ✦ smart-shuffle song: never suggest it again (kept in + /// `not_interested`). It leaves For You at once; a ✦ song leaves the queue (and is skipped + /// if it's playing). + pub(super) fn mark_not_interested(&mut self) { + let row = match self.focus { + Focus::Main if !self.lyrics_open => self.view.state.selected().and_then(|i| self.view.rows.get(i)).cloned(), + _ => None, + } + .filter(|r| r.kind == Kind::Track && (self.view.uri == FOR_YOU || self.is_rec(&r.uri))) + .or_else(|| self.now.clone().filter(|r| self.is_rec(&r.uri))); + let Some(row) = row else { + self.status = "X is for suggestions: a song in For You, or a ✦ song from smart shuffle.".into(); + return; + }; + if self.not_interested.insert(row.uri.clone()) + && let Some(d) = self.data_dir.as_deref() + { + discover::add_not_interested(d, &row.uri); + } + self.edit_cached(FOR_YOU, |v| v.retain(|r| r.uri != row.uri)); + if let Some(i) = self.recs.iter().position(|r| r.uri == row.uri) { + let idx = self.ctx.len() + i; + if self.now.as_ref().is_some_and(|n| n.uri == row.uri) { + self.next(false); + } + // later in the play order: take it out (the entry at the cursor is what plays now) + if let Some(p) = self.order.iter().position(|&o| o == idx).filter(|&p| p > self.cursor) { + self.order.remove(p); + } + self.refresh_queue_view(); + } + self.status = format!("Not interested in “{}”: it won't be suggested again.", row.title); + } + // ---------------------------------------------------------------- lyrics pub(super) fn toggle_lyrics(&mut self) { @@ -776,7 +811,10 @@ impl App { } let have: HashSet<&str> = self.ctx.iter().map(|r| r.uri.as_str()).collect(); let mut seen = HashSet::new(); - let recs: Vec = rows.into_iter().filter(|r| !have.contains(r.uri.as_str()) && seen.insert(r.uri.clone())).collect(); + let recs: Vec = rows + .into_iter() + .filter(|r| !have.contains(r.uri.as_str()) && !self.not_interested.contains(&r.uri) && seen.insert(r.uri.clone())) + .collect(); self.recs = recs; self.weave(); self.refresh_queue_view(); diff --git a/src/discover.rs b/src/discover.rs new file mode 100644 index 0000000..daf5654 --- /dev/null +++ b/src/discover.rs @@ -0,0 +1,342 @@ +//! "For You": songs picked from what you actually play, worked out on this machine. +//! +//! Every song played for 30 s goes in a local log (`~/.local/share/trill/plays`), which +//! never leaves the machine. From it trill takes seeds, counting each play less the older it +//! is (half as much every 14 days), with your newest liked songs filling in while the log is +//! short. It then asks Spotify, with the same requests trill makes while browsing, for: +//! - the radio of your top seed songs (what smart shuffle uses), and +//! - the top songs of artists Spotify lists as related to your top artists. +//! +//! Those are ranked here. Songs you've liked or marked "not interested" are left out, songs +//! you've been playing a lot are pushed down, and each further song by the same artist +//! counts half as much (3 at most), so no one artist takes over. Every row says why it's there. +//! +//! What goes to Spotify: the ids of up to 4 seed songs (their radio), up to 40 of your top +//! songs (to look up their artists), up to 16 artist ids (their pages) and the ids of the +//! songs suggested (for their titles and covers). The play log itself stays here. + +use std::{ + collections::{HashMap, HashSet}, + fs, + io::Write, + path::Path, +}; + +use futures_util::{StreamExt, stream}; +use librespot_core::Session; + +use crate::api::{self, Row, Rows}; + +pub const FOR_YOU: &str = "trill:foryou"; +const PLAYS: &str = "plays"; +const NOT_INTERESTED: &str = "not_interested"; +const HALF_LIFE_DAYS: f64 = 14.0; +const DAY: f64 = 86_400.0; +/// Suggestions shown. +const SHOW: usize = 50; +const SEED_SONGS: usize = 4; +const SEED_ARTISTS: usize = 4; +/// Related artists whose top songs are asked for. +const RELATED: usize = 12; +/// At most this many songs by one artist. +const PER_ARTIST: u32 = 3; +/// Below this many logged songs, the newest liked songs are seeds too. +const THIN_LOG: usize = 15; + +type Res = Result; + +/// One logged play: when (unix seconds), the song, and its title for the "why" column. +pub struct Play { + pub at: u64, + pub uri: String, + pub title: String, +} + +/// Note that `row` has played for 30 s: `unix secsurititleartist`, appended. +/// shortcut: the log is never trimmed (~100 bytes a song, ~2 MB a year of daily listening); it's +/// only read when For You refreshes, so it costs no memory meanwhile. +pub fn log_play(dir: &Path, row: &Row) { + let clean = |s: &str| s.replace(['\t', '\n', '\r'], " "); + let line = format!("{}\t{}\t{}\t{}\n", crate::app::unix_now(), row.uri, clean(&row.title), clean(&row.artist)); + let _ = fs::create_dir_all(dir); + if let Ok(mut f) = fs::OpenOptions::new().create(true).append(true).open(dir.join(PLAYS)) { + let _ = f.write_all(line.as_bytes()); + } +} + +pub fn read_plays(dir: &Path) -> Vec { + let text = fs::read_to_string(dir.join(PLAYS)).unwrap_or_default(); + text.lines() + .filter_map(|l| { + let mut f = l.split('\t'); + Some(Play { at: f.next()?.parse().ok()?, uri: f.next()?.to_string(), title: f.next().unwrap_or("").to_string() }) + }) + .collect() +} + +/// Songs you said you're not interested in (`X`), one uri per line. +pub fn not_interested(dir: &Path) -> HashSet { + fs::read_to_string(dir.join(NOT_INTERESTED)).unwrap_or_default().lines().map(String::from).filter(|l| !l.is_empty()).collect() +} + +pub fn add_not_interested(dir: &Path, uri: &str) { + let _ = fs::create_dir_all(dir); + if let Ok(mut f) = fs::OpenOptions::new().create(true).append(true).open(dir.join(NOT_INTERESTED)) { + let _ = writeln!(f, "{uri}"); + } +} + +/// How much each song counts as a seed: each play, halved for every 14 days since. +fn weights(plays: &[Play], now: u64) -> HashMap { + let mut w = HashMap::new(); + for p in plays { + let age = now.saturating_sub(p.at) as f64 / DAY; + *w.entry(p.uri.clone()).or_insert(0.0) += 0.5f64.powf(age / HALF_LIFE_DAYS); + } + w +} + +/// Seed songs, strongest first: the play log, plus (while it's short) the newest liked songs, +/// each counting as half a play that fades over a month. +fn seeds(plays: &[Play], liked: &[Row], now: u64) -> Vec<(String, f64)> { + let mut w = weights(plays, now); + if w.len() < THIN_LOG { + for r in liked.iter().filter(|r| r.kind == api::Kind::Track).take(50) { + let age = now.saturating_sub(r.added_at / 1000) as f64 / DAY; + w.entry(r.uri.clone()).or_insert(0.5 * 0.5f64.powf(age / 30.0)); + } + } + let mut v: Vec<(String, f64)> = w.into_iter().collect(); + v.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + v +} + +/// Plays in the last 30 days, per song. +fn recent_counts(plays: &[Play], now: u64) -> HashMap { + let mut c = HashMap::new(); + for p in plays.iter().filter(|p| now.saturating_sub(p.at) < 30 * 86_400) { + *c.entry(p.uri.clone()).or_insert(0) += 1; + } + c +} + +/// A song suggested by one source, with how strongly and why. +struct Candidate { + uri: String, + score: f64, + why: String, +} + +/// Merge the candidates for each song (scores add up, the strongest reason is kept), leave +/// out `exclude`, push down songs played lately (score / (1 + plays in 30 days)), then take +/// the best greedily, each further song by the same artist counting half as much. +/// The reason goes in `members`, which the table shows in its own column. +fn rank(cands: Vec, rows: &HashMap, exclude: &HashSet, recent: &HashMap, n: usize) -> Vec { + let mut merged: HashMap = HashMap::new(); // uri -> (total, best, why) + for c in cands.into_iter().filter(|c| !exclude.contains(&c.uri)) { + let e = merged.entry(c.uri).or_insert((0.0, 0.0, String::new())); + e.0 += c.score; + if c.score > e.1 { + (e.1, e.2) = (c.score, c.why); + } + } + let mut pool: Vec<(f64, &Row, String)> = merged + .into_iter() + .filter_map(|(uri, (score, _, why))| { + let row = rows.get(&uri)?; + Some((score / (1.0 + *recent.get(&uri).unwrap_or(&0) as f64), row, why)) + }) + .collect(); + // ties (and equal damped scores) go by uri, so the same input gives the same list + pool.sort_by(|a, b| b.0.total_cmp(&a.0).then_with(|| a.1.uri.cmp(&b.1.uri))); + let artist = |r: &Row| r.artist.split(", ").next().unwrap_or("").to_lowercase(); + let mut per_artist: HashMap = HashMap::new(); + let mut out = Vec::new(); + while out.len() < n { + let damped = |(s, r, _): &(f64, &Row, String)| { + let k = *per_artist.get(&artist(r)).unwrap_or(&0); + (k < PER_ARTIST).then(|| s * 0.5f64.powi(k as i32)) + }; + let Some(i) = (0..pool.len()).filter(|&i| damped(&pool[i]).is_some()).max_by(|&a, &b| { + damped(&pool[a]).unwrap_or(0.0).total_cmp(&damped(&pool[b]).unwrap_or(0.0)).then_with(|| pool[b].1.uri.cmp(&pool[a].1.uri)) + }) else { + break; + }; + let (_, row, why) = pool.remove(i); + *per_artist.entry(artist(row)).or_insert(0) += 1; + let mut r = row.clone(); + r.members = why; + out.push(r); + } + out +} + +/// Work out For You. `liked`: Liked Songs (seeds while the play log is short); `exclude`: +/// what's never suggested (your library and "not interested"). +pub async fn for_you(session: &Session, dir: &Path, liked: Rows, exclude: HashSet) -> Res> { + let now = crate::app::unix_now(); + let plays = read_plays(dir); + let seeds = seeds(&plays, &liked, now); + let Some(max) = seeds.first().map(|s| s.1) else { + return Err("play or like a few songs first: suggestions start from what you play".into()); + }; + let mut title: HashMap<&str, &str> = liked.iter().map(|r| (r.uri.as_str(), r.title.as_str())).collect(); + title.extend(plays.iter().filter(|p| !p.title.is_empty()).map(|p| (p.uri.as_str(), p.title.as_str()))); + + // your top artists: the first artist of each top song, adding up the songs' weights + let top: Vec = seeds.iter().take(40).map(|s| s.0.clone()).collect(); + let artist_of = api::track_artists(session, &top).await?; + let mut by_artist: HashMap = HashMap::new(); + for (uri, w) in seeds.iter().take(40) { + if let Some((a, name)) = artist_of.get(uri) { + by_artist.entry(a.clone()).or_insert((0.0, name.clone())).0 += w / max; + } + } + let mut seed_artists: Vec<(String, f64, String)> = by_artist.into_iter().map(|(a, (w, n))| (a, w, n)).collect(); + seed_artists.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + seed_artists.truncate(SEED_ARTISTS); + let artist_max = seed_artists.first().map_or(1.0, |a| a.1); + + // the radio of the top songs and the pages of the top artists, all at once (owned values: + // the requests run in parallel inside a spawned task) + let seed_songs: Vec<(String, f64)> = seeds.iter().take(SEED_SONGS).cloned().collect(); + let radios = stream::iter(seed_songs) + .map(|(uri, w)| { + let s = session.clone(); + async move { + let songs = api::station(&s, &uri).await; + (uri, w / max, songs) + } + }) + .buffer_unordered(8) + .collect::>(); + let pages = stream::iter(seed_artists.clone()) + .map(|(a, w, name)| { + let s = session.clone(); + async move { + let page = api::artist_overview(&s, &a).await; + (a, w / artist_max, name, page) + } + }) + .buffer_unordered(8) + .collect::>(); + let (radios, pages) = tokio::join!(radios, pages); + + // related artists, scored by the top artists that list them (earlier in a list counts more) + let seed_ids: HashSet<&str> = seed_artists.iter().map(|a| a.0.as_str()).collect(); + let mut related: HashMap = HashMap::new(); // uri -> (score, best part, why) + for (a, w, name, page) in &pages { + let rel = match page { + Ok((rel, _)) => rel, + Err(e) => { + log::warn!("For You: artist page {a}: {e}"); + continue; + } + }; + for (i, (uri, _)) in rel.iter().take(8).enumerate().filter(|(_, (u, _))| !seed_ids.contains(u.as_str())) { + let part = w * 0.9f64.powi(i as i32); + let e = related.entry(uri.clone()).or_insert((0.0, 0.0, String::new())); + e.0 += part; + if part > e.1 { + (e.1, e.2) = (part, name.clone()); + } + } + } + let mut related: Vec<(String, f64, String)> = related.into_iter().map(|(u, (s, _, why))| (u, s, why)).collect(); + related.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + related.truncate(RELATED); + let related_pages = stream::iter(related) + .map(|(uri, w, why)| { + let s = session.clone(); + async move { (w, why, api::artist_overview(&s, &uri).await) } + }) + .buffer_unordered(8) + .collect::>() + .await; + + let mut cands = Vec::new(); + for (seed, w, songs) in &radios { + let why = format!("radio · {}", title.get(seed.as_str()).copied().unwrap_or("a song you play")); + cands.extend(songs.iter().take(25).enumerate().map(|(i, u)| Candidate { uri: u.clone(), score: w * 0.97f64.powi(i as i32), why: why.clone() })); + } + for (w, why, page) in &related_pages { + let Ok((_, top)) = page else { continue }; + let why = format!("like {why}"); + cands.extend(top.iter().take(4).enumerate().map(|(i, u)| Candidate { uri: u.clone(), score: 0.8 * w * 0.85f64.powi(i as i32), why: why.clone() })); + } + // the seeds are songs you play already + let mut exclude = exclude; + exclude.extend(seeds.iter().take(SEED_SONGS).map(|s| s.0.clone())); + let mut want: Vec = cands.iter().map(|c| c.uri.clone()).filter(|u| !exclude.contains(u)).collect(); + want.sort(); + want.dedup(); + let rows: HashMap = api::track_rows(session, want).await?.into_iter().map(|r| (r.uri.clone(), r)).collect(); + let out = rank(cands, &rows, &exclude, &recent_counts(&plays, now), SHOW); + if out.is_empty() { + return Err("Spotify had no suggestions this time; R tries again".into()); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn row(uri: &str, artist: &str) -> Row { + Row { + uri: uri.into(), + title: uri.into(), + artist: artist.into(), + album: String::new(), + duration_ms: 1, + kind: api::Kind::Track, + art: None, + added_at: 0, + members: String::new(), + plays: 0, + } + } + + #[test] + fn plays_fade_with_age() { + let now = 100 * 86_400; + let p = |days: u64, uri: &str| Play { at: now - days * 86_400, uri: uri.into(), title: String::new() }; + let w = weights(&[p(0, "a"), p(14, "b"), p(28, "c"), p(28, "c")], now); + assert!((w["a"] - 1.0).abs() < 1e-9 && (w["b"] - 0.5).abs() < 1e-9 && (w["c"] - 0.5).abs() < 1e-9); + assert_eq!(recent_counts(&[p(1, "a"), p(29, "a"), p(31, "a")], now)["a"], 2); + // a short log borrows the newest liked songs, below what you actually play + let s = seeds(&[p(0, "a")], &[row("liked", "x")], now); + assert_eq!(s[0].0, "a"); + assert_eq!(s[1].0, "liked"); + } + + #[test] + fn ranks_diverse_explains_and_respects_no() { + let mut rows = HashMap::new(); + for (u, a) in [("a1", "A"), ("a2", "A"), ("a3", "A"), ("a4", "A, Feat"), ("b1", "B"), ("liked", "C"), ("tired", "D"), ("no", "E")] { + rows.insert(u.to_string(), row(u, a)); + } + let c = |uri: &str, score: f64, why: &str| Candidate { uri: uri.into(), score, why: why.into() }; + let cands = vec![ + c("a1", 1.0, "radio · x"), + c("a2", 0.95, "radio · x"), + c("a3", 0.9, "radio · x"), + c("a4", 0.89, "radio · x"), + c("b1", 0.4, "like B"), + c("b1", 0.3, "radio · y"), // a second source adds up; the stronger reason stays + c("liked", 5.0, "radio · x"), + c("tired", 3.0, "radio · x"), + c("no", 4.0, "radio · x"), + c("gone", 9.0, "radio · x"), // no metadata: dropped + ]; + let exclude: HashSet = ["liked", "no"].map(String::from).into(); + let recent: HashMap = [("tired".to_string(), 9)].into(); + let out = rank(cands, &rows, &exclude, &recent, 10); + let got: Vec<&str> = out.iter().map(|r| r.uri.as_str()).collect(); + // B's merged 0.7 beats A's second song (0.95 / 2); "tired" (3.0 / 10) beats A's third + // (0.9 / 4); A's fourth is past the cap of 3 + assert_eq!(got, ["a1", "b1", "a2", "tired", "a3"]); + assert_eq!(out[1].members, "like B"); + assert_eq!(out[0].members, "radio · x"); + } +} diff --git a/src/main.rs b/src/main.rs index a55be35..d955cd5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,6 +13,7 @@ mod app; mod audio; mod auth; mod config; +mod discover; mod engine; mod library; mod theme; @@ -736,6 +737,8 @@ async fn run(cfg: Config) -> i32 { } app.soloist_missing = cfg.soloist_missing(); app.cache_dir = Some(cfg.cache_dir.clone()); + app.not_interested = discover::not_interested(&cfg.data_dir); + app.data_dir = Some(cfg.data_dir.clone()); app.art_on = img_picker.is_some() && app.audio.art; app.img_picker = img_picker; app.load_playlists(); @@ -854,6 +857,7 @@ async fn run(cfg: Config) -> i32 { Some(cmd) = remote_rx.recv() => { app.on_remote(cmd); dirty = true; } _ = tick.tick(), if app.playing => { app.check_resume(); + app.note_play(); dirty = true; } } diff --git a/src/ui.rs b/src/ui.rs index c7d0086..3eac67f 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -186,7 +186,7 @@ pub fn draw_splash(f: &mut Frame, playlists: &[String]) { } None => side, }; - let fixed = ["♥ Liked Songs", "≡ Queue", "⌕ Search"]; + let fixed = ["♥ Liked Songs", "◉ Albums", "◈ Artists", "✦ For You", "≡ Queue", "⌕ Search"]; // as App::new lists them let items: Vec = fixed.iter().copied().chain(playlists.iter().map(String::as_str)).map(ListItem::new).collect(); f.render_widget(List::new(items).block(block("Library", false)), side); f.render_widget(Block::bordered().border_type(BorderType::Rounded).border_style(Style::new().dim()).title(" trill "), main); @@ -319,7 +319,7 @@ fn draw_table(f: &mut Frame, app: &mut App, main: Rect) { (show_album, Constraint::Length(album_w), Line::from("Album")), (true, Constraint::Fill(1), Line::default()), (show_added, Constraint::Length(10), Line::from("Added")), - (for_w > 0, Constraint::Length(for_w.max(3)), Line::from("For")), + (for_w > 0, Constraint::Length(for_w.max(3)), Line::from(if app.view.uri == crate::discover::FOR_YOU { "Why" } else { "For" })), (plays_w > 0, Constraint::Length(plays_w.max(5)), Line::from("Plays").right_aligned()), (true, Constraint::Length(time_w), Line::from("Time").right_aligned()), ] { @@ -538,6 +538,7 @@ const HELP: [(&str, &[(&str, &str)]); 4] = [ ("D D", "remove from the playlist · queue"), ("y Y", "copy link: highlighted · open list"), ("I", "private session ⊘ on / off (6 h)"), + ("X", "not interested (For You, ✦ songs)"), ]), ("Browse", &[ ("↑↓ jk", "move (PgUp/PgDn, g/G jump)"), @@ -552,8 +553,7 @@ const HELP: [(&str, &[(&str, &str)]); 4] = [ ("R", "reload the current list"), ]), ("View", &[ - ("L", "lyrics"), - ("i t", "album art on / off · next theme"), + ("L i t", "lyrics · album art · next theme"), ("e E", "next EQ preset / EQ panel"), ("? q", "this help · quit (also Ctrl-C)"), ]), From 5ae529701626c0cac1f587679c319bf2cf16db23 Mon Sep 17 00:00:00 2001 From: Junaid Irfan Date: Tue, 24 Nov 2026 01:48:23 -0500 Subject: [PATCH 2/2] For You: mix the sources too, each further pick from one song's radio or one artist's neighbours counting 0.8 --- src/discover.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/discover.rs b/src/discover.rs index daf5654..11b398c 100644 --- a/src/discover.rs +++ b/src/discover.rs @@ -129,7 +129,8 @@ struct Candidate { /// Merge the candidates for each song (scores add up, the strongest reason is kept), leave /// out `exclude`, push down songs played lately (score / (1 + plays in 30 days)), then take -/// the best greedily, each further song by the same artist counting half as much. +/// the best greedily: each further song by the same artist counts half as much, and each +/// further one from the same source (one song's radio, one artist's neighbours) 0.8 as much. /// The reason goes in `members`, which the table shows in its own column. fn rank(cands: Vec, rows: &HashMap, exclude: &HashSet, recent: &HashMap, n: usize) -> Vec { let mut merged: HashMap = HashMap::new(); // uri -> (total, best, why) @@ -151,11 +152,13 @@ fn rank(cands: Vec, rows: &HashMap, exclude: &HashSet = HashMap::new(); + let mut per_source: HashMap = HashMap::new(); let mut out = Vec::new(); while out.len() < n { - let damped = |(s, r, _): &(f64, &Row, String)| { + let damped = |(s, r, why): &(f64, &Row, String)| { let k = *per_artist.get(&artist(r)).unwrap_or(&0); - (k < PER_ARTIST).then(|| s * 0.5f64.powi(k as i32)) + let src = *per_source.get(why).unwrap_or(&0); + (k < PER_ARTIST).then(|| s * 0.5f64.powi(k as i32) * 0.8f64.powi(src as i32)) }; let Some(i) = (0..pool.len()).filter(|&i| damped(&pool[i]).is_some()).max_by(|&a, &b| { damped(&pool[a]).unwrap_or(0.0).total_cmp(&damped(&pool[b]).unwrap_or(0.0)).then_with(|| pool[b].1.uri.cmp(&pool[a].1.uri)) @@ -164,6 +167,7 @@ fn rank(cands: Vec, rows: &HashMap, exclude: &HashSet = [("tired".to_string(), 9)].into(); let out = rank(cands, &rows, &exclude, &recent, 10); let got: Vec<&str> = out.iter().map(|r| r.uri.as_str()).collect(); - // B's merged 0.7 beats A's second song (0.95 / 2); "tired" (3.0 / 10) beats A's third - // (0.9 / 4); A's fourth is past the cap of 3 + // B's merged 0.7 beats A's second song (0.95 × ½ × 0.8 for its source); "tired" + // (3.0 / 10 × 0.8²) beats A's third (0.9 × ¼ × 0.8²); A's fourth is past the cap of 3 assert_eq!(got, ["a1", "b1", "a2", "tired", "a3"]); assert_eq!(out[1].members, "like B"); assert_eq!(out[0].members, "radio · x");