Add genre mixes from clustering recent listens

A new cluster_mix_rule clusters a Listenbrainz user's listens from the
last few months by MusicBrainz genre (with tracks played in the same
session pulled together) and maintains one Subsonic playlist per cluster,
filled with the cluster's most played tracks plus unheard library songs
from the best matching library genres.

- listenbrainz: fetch raw listens since a timestamp and bulk recording
  genres, handling rate limits
- cluster: tag TF-IDF + co-listen smoothing, spherical k-means with k
  chosen by silhouette score
- mix: match cluster profiles to library genres and pick songs, with a
  per-artist cap; reuse playlists across rebuilds by genre overlap
- subsonic: getGenres, getSongsByGenre, rename/delete playlist, genre and
  MBID fields on tracks, API error detection
- daemon, migration, POST/GET /api/playlist/mix and README docs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018opPJMJjLWr4RqdG6vuK6p
This commit is contained in:
Claude committed 2026-11-13 14:53:29 +00:00
1 parent e082209bd2
commit 18b3f0974e
13 files changed
+1728 -5

No files matched your search

+151
View File
@@ -43,6 +43,30 @@ struct GetPlaylistResponse {
type CreatePlaylistResponse = GetPlaylistResponse;
#[derive(Deserialize)]
struct GetGenresResponse {
genres: GenreList,
}
#[derive(Deserialize)]
struct GenreList {
#[serde(default)]
genre: Vec<Genre>,
}
#[derive(Deserialize, Debug, Clone)]
pub struct Genre {
pub value: String,
#[serde(rename = "songCount", default)]
pub song_count: usize,
}
#[derive(Deserialize)]
struct SongsByGenreResponse {
#[serde(rename = "songsByGenre")]
songs_by_genre: SearchResponseSongs,
}
struct AuthParams {
salt: String,
hash: String,
@@ -51,6 +75,8 @@ struct AuthParams {
#[derive(Debug, Error)]
pub enum SubsonicError {
Reqwest(reqwest::Error),
Api(String),
Json(serde_json::Error),
}
impl Display for SubsonicError {
@@ -194,6 +220,131 @@ impl Subsonic {
self.get_playlist(playlist_id).await
}
/// Authentication and format parameters common to every request
fn base_params(&self) -> Vec<(&'static str, String)> {
let auth_params = self.auth_params();
vec![
("u", self.username.to_string()),
("s", auth_params.salt),
("t", auth_params.hash),
("v", String::from("16")),
("c", String::from("playlistd")),
("f", String::from("json")),
]
}
async fn request<T: serde::de::DeserializeOwned>(
&self,
endpoint: &str,
params: &[(&'static str, String)],
) -> Result<T, SubsonicError> {
let mut query = self.base_params();
query.extend_from_slice(params);
let response = self
.client
.get(format!("{}/{}", self.base, endpoint))
.query(&query)
.send()
.await
.map_err(SubsonicError::Reqwest)?
.json::<SubsonicResponse<serde_json::Value>>()
.await
.map_err(SubsonicError::Reqwest)?
.subsonic_response;
if response.get("status").and_then(|s| s.as_str()) == Some("failed") {
return Err(SubsonicError::Api(
response
.pointer("/error/message")
.and_then(|m| m.as_str())
.unwrap_or("unknown error")
.to_string(),
));
}
serde_json::from_value(response).map_err(SubsonicError::Json)
}
/// All genres in the library
pub async fn get_genres(&self) -> Result<Vec<Genre>, SubsonicError> {
Ok(self
.request::<GetGenresResponse>("getGenres", &[])
.await?
.genres
.genre)
}
/// Up to `limit` songs with the given genre
pub async fn songs_by_genre(
&self,
genre: &str,
limit: usize,
) -> Result<Vec<Track>, SubsonicError> {
// Subsonic caps a single page at 500
const PAGE: usize = 500;
let mut songs = vec![];
while songs.len() < limit {
let count = PAGE.min(limit - songs.len());
let page = self
.request::<SongsByGenreResponse>(
"getSongsByGenre",
&[
("genre", genre.to_string()),
("count", count.to_string()),
("offset", songs.len().to_string()),
],
)
.await?
.songs_by_genre
.song;
let done = page.len() < count;
songs.extend(page);
if done {
break;
}
}
Ok(songs)
}
pub async fn rename_playlist(
&self,
playlist_id: &str,
name: &str,
) -> Result<(), SubsonicError> {
self.request::<serde_json::Value>(
"updatePlaylist",
&[
("playlistId", playlist_id.to_string()),
("name", name.to_string()),
],
)
.await?;
Ok(())
}
/// Replace all of a playlist's songs
pub async fn replace_playlist_songs(
&self,
playlist_id: &str,
song_ids: Vec<String>,
) -> Result<Playlist, SubsonicError> {
let playlist = self.get_playlist(playlist_id).await?;
self.update_playlist(
playlist_id.to_string(),
song_ids,
(0..playlist.song_count).collect(),
)
.await
}
pub async fn delete_playlist(&self, playlist_id: &str) -> Result<(), SubsonicError> {
self.request::<serde_json::Value>("deletePlaylist", &[("id", playlist_id.to_string())])
.await?;
Ok(())
}
}
#[derive(Default)]