diff --git a/crates/Cargo.lock b/crates/Cargo.lock index 0903732ea..9e0e0d922 100644 --- a/crates/Cargo.lock +++ b/crates/Cargo.lock @@ -5560,6 +5560,7 @@ dependencies = [ "qbz-player", "qbz-qobuz", "qbz-radio", + "qbz-reco", "serde", "serde_json", "thiserror 2.0.18", diff --git a/crates/qbz-core/Cargo.toml b/crates/qbz-core/Cargo.toml index d738c471d..f087a3274 100644 --- a/crates/qbz-core/Cargo.toml +++ b/crates/qbz-core/Cargo.toml @@ -13,6 +13,7 @@ qbz-qobuz = { path = "../qbz-qobuz" } qbz-radio = { path = "../qbz-radio" } qbz-integrations = { path = "../qbz-integrations" } qbz-offline-cache = { path = "../qbz-offline-cache" } +qbz-reco = { path = "../qbz-reco" } # Async tokio = { workspace = true } diff --git a/crates/qbz-core/src/core.rs b/crates/qbz-core/src/core.rs index dcceaff92..b32effe27 100644 --- a/crates/qbz-core/src/core.rs +++ b/crates/qbz-core/src/core.rs @@ -214,6 +214,10 @@ pub struct QbzCore { /// data-dir path) via `set_musicbrainz_cache`. Methods read the /// cache before hitting the network and persist on miss. musicbrainz_cache: Arc>>, + /// Per-user artist-vector store for the playlist "Suggested Songs" engine. + /// Opened by the frontend (owns the data dir) via `set_artist_vectors`. + /// tokio Mutex because the suggestions engine holds it across `.await`s. + artist_vectors: Arc>>, /// Whether the core is initialized initialized: Arc>, /// D8 guard: true when the current queue was built from an OFFLINE-ONLY @@ -238,6 +242,7 @@ impl QbzCore { player: Arc::new(player), musicbrainz: Arc::new(MusicBrainzClient::new()), musicbrainz_cache: Arc::new(std::sync::Mutex::new(None)), + artist_vectors: Arc::new(tokio::sync::Mutex::new(None)), initialized: Arc::new(RwLock::new(false)), queue_offline_only: Arc::new(std::sync::atomic::AtomicBool::new(false)), } @@ -267,6 +272,18 @@ impl QbzCore { } } + /// Install the per-user artist-vector store (playlist Suggested Songs). The + /// frontend owns the data path and opens it via + /// `qbz_reco::ArtistVectorStore::open_at`. + pub async fn set_artist_vectors(&self, store: qbz_reco::ArtistVectorStore) { + *self.artist_vectors.lock().await = Some(store); + } + + /// Drop the per-user artist-vector store on logout. + pub async fn clear_artist_vectors(&self) { + *self.artist_vectors.lock().await = None; + } + /// Initialize the core /// /// This should be called once at startup to set up all subsystems. @@ -1937,6 +1954,72 @@ impl QbzCore { .map_err(|e| CoreError::Internal(e.to_string())) } + /// Generate playlist "Suggested Songs" via the artist_vectors engine. + /// Resolves each playlist artist NAME to a confident MusicBrainz id, then + /// runs the SuggestionsEngine over the core-owned clients + the per-user + /// vector store. The names come from the playlist's own Qobuz tracks (so + /// they are already canonical — the Tauri command's extra Qobuz-name + /// re-fetch is unnecessary; `qobuz_id` is accepted for forward use). + pub async fn generate_playlist_suggestions( + &self, + artists: Vec<(Option, String)>, + exclude_track_ids: Vec, + include_reasons: bool, + config: Option, + ) -> Result { + use std::collections::HashSet; + + if artists.is_empty() { + return Ok(qbz_reco::SuggestionResult { + tracks: Vec::new(), + source_artists: Vec::new(), + playlist_artists_count: 0, + similar_artists_count: 0, + }); + } + + // Resolve each artist name to a confident MusicBrainz id, deduped. + let mut resolved: Vec<(String, String)> = Vec::new(); + let mut seen: HashSet = HashSet::new(); + for (_qobuz_id, name) in &artists { + if let Ok(Some(r)) = self.musicbrainz_resolve_artist(name).await { + if seen.insert(r.mbid.clone()) { + resolved.push((r.mbid, name.clone())); + } + } + } + + if resolved.is_empty() { + log::warn!("[suggestions] no playlist artists resolved to MusicBrainz ids"); + return Ok(qbz_reco::SuggestionResult { + tracks: Vec::new(), + source_artists: Vec::new(), + playlist_artists_count: artists.len(), + similar_artists_count: 0, + }); + } + + let config = config.unwrap_or_default(); + let builder = Arc::new(qbz_reco::ArtistVectorBuilder::new( + self.artist_vectors.clone(), + self.musicbrainz.clone(), + self.musicbrainz_cache.clone(), + self.client.clone(), + qbz_reco::RelationshipWeights::default(), + )); + let engine = qbz_reco::SuggestionsEngine::new( + self.artist_vectors.clone(), + builder, + self.client.clone(), + config, + ); + + let exclude: HashSet = exclude_track_ids.into_iter().collect(); + engine + .generate_suggestions(&resolved, &exclude, include_reasons) + .await + } + /// Fetch the artist metadata (location, life_span, genre seeds) for /// the Origin section of the artist network sidebar. Resolves the /// real country from the begin_area hierarchy when a city-level diff --git a/crates/qbz-reco/src/builder.rs b/crates/qbz-reco/src/builder.rs index 4ceafca48..006c2a71f 100644 --- a/crates/qbz-reco/src/builder.rs +++ b/crates/qbz-reco/src/builder.rs @@ -27,12 +27,14 @@ use crate::weights::RelationshipWeights; pub struct ArtistVectorBuilder { /// Vector store for persistence store: Arc>>, - /// MusicBrainz client for relationship data (behind Mutex for shared ownership) - mb_client: Arc>, - /// MusicBrainz cache - mb_cache: Arc>>, - /// Qobuz client for similar artists - qobuz_client: Arc>, + /// MusicBrainz client (Send+Sync, no outer lock — matches qbz-core's + /// `Arc`). + mb_client: Arc, + /// MusicBrainz cache (std::sync::Mutex — matches qbz-core; locked only for + /// short, await-free windows so no guard crosses an `.await`). + mb_cache: Arc>>, + /// Qobuz client for similar artists (`Option` = no active session). + qobuz_client: Arc>>, /// Configurable weights weights: RelationshipWeights, } @@ -54,9 +56,9 @@ impl ArtistVectorBuilder { /// Create a new builder with the given dependencies pub fn new( store: Arc>>, - mb_client: Arc>, - mb_cache: Arc>>, - qobuz_client: Arc>, + mb_client: Arc, + mb_cache: Arc>>, + qobuz_client: Arc>>, weights: RelationshipWeights, ) -> Self { Self { @@ -167,7 +169,10 @@ impl ArtistVectorBuilder { ) -> Result<(SparseVector, usize), String> { // Try cache first let cached = { - let guard__ = self.mb_cache.lock().await; + let guard__ = self + .mb_cache + .lock() + .map_err(|_| "MusicBrainz cache lock poisoned")?; let cache = guard__ .as_ref() .ok_or("No active session - please log in")?; @@ -177,20 +182,22 @@ impl ArtistVectorBuilder { let relations = if let Some(rel) = cached { rel } else { - // Fetch from API - let mb_client = self.mb_client.lock().await; - let response = mb_client + // Fetch from API (mb_client is Send+Sync; no lock needed) + let response = self + .mb_client .get_artist_with_relations(artist_mbid) .await .map_err(|e| e.to_string())?; - drop(mb_client); // Extract relationships from raw response let extracted = extract_relationships(&response); // Cache it { - let guard__ = self.mb_cache.lock().await; + let guard__ = self + .mb_cache + .lock() + .map_err(|_| "MusicBrainz cache lock poisoned")?; let cache = guard__ .as_ref() .ok_or("No active session - please log in")?; @@ -250,7 +257,10 @@ impl ArtistVectorBuilder { qobuz_artist_id: u64, ) -> Result<(SparseVector, usize), String> { let similar = { - let client = self.qobuz_client.read().await; + let guard__ = self.qobuz_client.read().await; + let client = guard__ + .as_ref() + .ok_or("No active session - please log in")?; client .get_similar_artists(qobuz_artist_id, 20, 0) .await diff --git a/crates/qbz-reco/src/suggestions.rs b/crates/qbz-reco/src/suggestions.rs index ecf25ad86..6468b44f9 100644 --- a/crates/qbz-reco/src/suggestions.rs +++ b/crates/qbz-reco/src/suggestions.rs @@ -109,7 +109,7 @@ pub struct SuggestionsEngine { /// Vector builder for lazy construction builder: Arc, /// Qobuz client for track search - qobuz_client: Arc>, + qobuz_client: Arc>>, /// Configuration config: SuggestionConfig, } @@ -119,7 +119,7 @@ impl SuggestionsEngine { pub fn new( store: Arc>>, builder: Arc, - qobuz_client: Arc>, + qobuz_client: Arc>>, config: SuggestionConfig, ) -> Self { Self { @@ -357,7 +357,10 @@ impl SuggestionsEngine { let step4c_start = Instant::now(); // Get client for Qobuz API calls - let client = self.qobuz_client.read().await; + let guard__ = self.qobuz_client.read().await; + let client = guard__ + .as_ref() + .ok_or_else(|| "No active session - please log in".to_string())?; // For each playlist artist, get their Qobuz similar artists let mut qobuz_similar_ids: HashSet = HashSet::new(); @@ -627,7 +630,11 @@ impl SuggestionsEngine { } }; - let client = self.qobuz_client.read().await; + let guard__ = self.qobuz_client.read().await; + let Some(client) = guard__.as_ref() else { + log::warn!("[SuggestionsEngine] No active Qobuz session; skipping"); + return Vec::new(); + }; // Step 1: Validate artist exists in Qobuz with their own catalog // This prevents searching for session musicians who don't have artist pages