Mix known songs into discover mixes at a fixed ratio
"Play mix" in the discover UI used to spread new songs through the whole library playlist, so the share of new songs depended on how many there were. It now plays the new songs with songs the user has played mixed in evenly at the rule's familiar_ratio (30% by default), the same ratio that sets how much of the Subsonic playlist is familiar. Which songs in each mix playlist were played recently is now recorded when the mix is built (cluster_mix_playlist.known_song_ids) and returned with the mix; the UI marks them as "Played". Mixes built before this fall back to using the library songs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018opPJMJjLWr4RqdG6vuK6p
This commit is contained in:
11 files changed
+92
-22
No files matched your search
@@ -106,7 +106,7 @@ VALUES (gen_random_uuid(), 'jellywx', 3, 50);
|
||||
| `months` | 3 | Months of listening history to cluster |
|
||||
| `cluster_count` | automatic | Number of mixes |
|
||||
| `playlist_size` | 50 | Songs per mix |
|
||||
| `familiar_ratio` | 0.3 | Share of each mix taken from recently played tracks |
|
||||
| `familiar_ratio` | 0.3 | Share of each mix made of songs you've played recently (also used by the discover UI's "Play mix") |
|
||||
| `name_template` | `Mix: {label}` | Playlist name; `{label}` becomes the mix's top genres |
|
||||
| `refresh_hours` | 24 | How often to rebuild the mixes |
|
||||
| `discovery_count`| 15 | New songs (not in your library) to suggest per mix |
|
||||
@@ -131,6 +131,10 @@ In the UI, songs from your library stream from Subsonic. New songs are found on
|
||||
installed on the server (keep it up to date: YouTube changes often break older versions). You can
|
||||
like a new song to keep it in "Liked new songs", or hide it so it isn't suggested again.
|
||||
|
||||
"Play mix" plays a mix's new songs in random order with songs you already know (the songs in the
|
||||
mix you've played recently) mixed in evenly, so that `familiar_ratio` of what you hear is familiar.
|
||||
If a mix has too few known songs to keep that ratio, all of them are used.
|
||||
|
||||
Build it with:
|
||||
|
||||
```sh
|
||||
|
||||
@@ -211,7 +211,7 @@ export function App() {
|
||||
{route.view === "liked" ? (
|
||||
<LikedView liked={liked} player={player} onStatus={onStatus} />
|
||||
) : detail ? (
|
||||
<MixView mix={detail} player={player} onStatus={onStatus} />
|
||||
<MixView mix={detail} knownRatio={rule?.familiar_ratio ?? 0.3} player={player} onStatus={onStatus} />
|
||||
) : (
|
||||
mixId && <div className="notice"><span className="spinner" /> Loading…</div>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo } from "react";
|
||||
import { MixDetail, mixTitle, Suggestion, SuggestionStatus } from "./api";
|
||||
import { fromSong, fromSuggestion, interleave, QueueItem } from "./queue";
|
||||
import { fromSong, fromSuggestion, mixAtRatio, QueueItem, shuffled } from "./queue";
|
||||
import { Player } from "./usePlayer";
|
||||
import { TrackRow } from "./TrackRow";
|
||||
import * as Icon from "./icons";
|
||||
@@ -37,15 +37,24 @@ export function SuggestionActions({ s, onStatus }: { s: Suggestion; onStatus: (s
|
||||
|
||||
type Props = {
|
||||
mix: MixDetail;
|
||||
/** Share of "Play mix" made of songs the user already knows */
|
||||
knownRatio: number;
|
||||
player: Player;
|
||||
onStatus: (s: Suggestion, status: SuggestionStatus) => void;
|
||||
};
|
||||
|
||||
export function MixView({ mix, player, onStatus }: Props) {
|
||||
export function MixView({ mix, knownRatio, player, onStatus }: Props) {
|
||||
const fresh = useMemo(() => mix.suggestions.map(fromSuggestion), [mix.suggestions]);
|
||||
const library = useMemo(() => mix.songs.map(fromSong), [mix.songs]);
|
||||
// clicking a row plays through everything shown, new songs first
|
||||
const all = useMemo(() => [...fresh, ...library], [fresh, library]);
|
||||
const knownIds = useMemo(() => new Set(mix.known_song_ids), [mix.known_song_ids]);
|
||||
// mixes built before songs were marked as known fall back to the whole library
|
||||
const known = useMemo(
|
||||
() => (knownIds.size ? library.filter((_, i) => knownIds.has(mix.songs[i].id)) : library),
|
||||
[library, knownIds, mix.songs],
|
||||
);
|
||||
// clicking a new song plays the new songs in order, with known songs mixed in
|
||||
const mixed = useMemo(() => mixAtRatio(fresh, known, knownRatio), [fresh, known, knownRatio]);
|
||||
const percent = Math.round(Math.min(Math.max(knownRatio, 0), 1) * 100);
|
||||
const title = mixTitle(mix);
|
||||
const h = hue(mix.tags.join());
|
||||
|
||||
@@ -65,10 +74,13 @@ export function MixView({ mix, player, onStatus }: Props) {
|
||||
{mix.tags.map((t) => <li key={t}>{t}</li>)}
|
||||
</ul>
|
||||
<p className="mix-counts">
|
||||
{mix.songs.length} from your library · {mix.suggestions.length} new
|
||||
{mix.suggestions.length} new · {mix.songs.length} from your library
|
||||
{knownIds.size > 0 && <>, {knownIds.size} you've played</>}
|
||||
</p>
|
||||
<div className="mix-buttons">
|
||||
<button className="primary" onClick={() => play(interleave(library, fresh))} disabled={!all.length}>
|
||||
<button className="primary" disabled={!fresh.length && !known.length}
|
||||
title={`New songs, with ${percent}% songs you already know mixed in`}
|
||||
onClick={() => play(fresh.length ? mixAtRatio(shuffled(fresh), shuffled(known), knownRatio) : shuffled(known))}>
|
||||
<Icon.Shuffle size={16} /> Play mix
|
||||
</button>
|
||||
<button onClick={() => play(fresh)} disabled={!fresh.length}>
|
||||
@@ -91,7 +103,7 @@ export function MixView({ mix, player, onStatus }: Props) {
|
||||
number={i + 1}
|
||||
active={isActive(fresh[i])}
|
||||
status={player.status}
|
||||
onPlay={() => play(all, i)}
|
||||
onPlay={() => play(mixed, mixed.indexOf(fresh[i]))}
|
||||
meta={<span className="match" title="How well its genres fit this mix">{Math.round(s.score * 100)}% match</span>}
|
||||
actions={<SuggestionActions s={s} onStatus={onStatus} />}
|
||||
/>
|
||||
@@ -110,8 +122,9 @@ export function MixView({ mix, player, onStatus }: Props) {
|
||||
number={i + 1}
|
||||
active={isActive(library[i])}
|
||||
status={player.status}
|
||||
onPlay={() => play(all, fresh.length + i)}
|
||||
onPlay={() => play(library, i)}
|
||||
duration={song.duration}
|
||||
meta={knownIds.has(song.id) ? <span className="played" title="You've played this recently">Played</span> : undefined}
|
||||
/>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
+8
-1
@@ -4,6 +4,8 @@ export type Rule = {
|
||||
months: number;
|
||||
playlist_size: number;
|
||||
discovery_count: number;
|
||||
/** Share of a mix made of songs the user already knows */
|
||||
familiar_ratio: number;
|
||||
last_run: string | null;
|
||||
};
|
||||
|
||||
@@ -40,7 +42,12 @@ export type Suggestion = {
|
||||
youtube_id: string | null;
|
||||
};
|
||||
|
||||
export type MixDetail = MixSummary & { songs: Song[]; suggestions: Suggestion[] };
|
||||
export type MixDetail = MixSummary & {
|
||||
songs: Song[];
|
||||
/** Songs in `songs` the user played recently */
|
||||
known_song_ids: string[];
|
||||
suggestions: Suggestion[];
|
||||
};
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const response = await fetch(`/api/discover${path}`, init);
|
||||
|
||||
+23
-8
@@ -32,16 +32,31 @@ export const fromSuggestion = (s: Suggestion): QueueItem => ({
|
||||
suggestionId: s.id,
|
||||
});
|
||||
|
||||
/** Spread new songs evenly through the library songs */
|
||||
export function interleave(library: QueueItem[], fresh: QueueItem[]): QueueItem[] {
|
||||
if (fresh.length === 0) return library;
|
||||
/**
|
||||
* Mix known songs into new ones so that `ratio` of the result is known songs, spread evenly.
|
||||
* If there aren't enough known songs to keep the ratio, all of them are used.
|
||||
*/
|
||||
export function mixAtRatio(fresh: QueueItem[], known: QueueItem[], ratio: number): QueueItem[] {
|
||||
const r = Math.min(Math.max(ratio, 0), 1);
|
||||
const wanted = r >= 1 ? known.length : Math.round((fresh.length * r) / (1 - r));
|
||||
const k = Math.min(wanted, known.length);
|
||||
const total = fresh.length + k;
|
||||
const out: QueueItem[] = [];
|
||||
const every = Math.max(1, Math.round((library.length + fresh.length) / fresh.length));
|
||||
let l = 0;
|
||||
let f = 0;
|
||||
for (let i = 0; l < library.length || f < fresh.length; i++) {
|
||||
const takeFresh = (i % every === every - 1 && f < fresh.length) || l >= library.length;
|
||||
out.push(takeFresh ? fresh[f++] : library[l++]);
|
||||
let n = 0;
|
||||
for (let i = 0; i < total; i++) {
|
||||
// a known song wherever the running count of known songs steps up
|
||||
const isKnown = Math.floor(((i + 1) * k) / total) > Math.floor((i * k) / total);
|
||||
out.push(isKnown ? known[n++] : fresh[f++]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function shuffled<T>(items: T[]): T[] {
|
||||
const out = [...items];
|
||||
for (let i = out.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[out[i], out[j]] = [out[j], out[i]];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -438,6 +438,15 @@ h2 {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.played {
|
||||
padding: 1px 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--surface-2);
|
||||
color: var(--muted);
|
||||
font-size: 0.75rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.track-duration {
|
||||
color: var(--muted);
|
||||
font-size: 0.85rem;
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Songs in the mix playlist that the user played in the clustered period
|
||||
ALTER TABLE "cluster_mix_playlist"
|
||||
ADD COLUMN known_song_ids TEXT[] NOT NULL DEFAULT '{}';
|
||||
@@ -196,10 +196,11 @@ pub async fn build_mixes(
|
||||
.rename_playlist(&old.playlist_id, &name)
|
||||
.await?;
|
||||
sqlx::query!(
|
||||
r#"UPDATE "cluster_mix_playlist" SET tags = $1, name = $2, position = $3 WHERE id = $4"#,
|
||||
r#"UPDATE "cluster_mix_playlist" SET tags = $1, name = $2, position = $3, known_song_ids = $4 WHERE id = $5"#,
|
||||
&mix.tags,
|
||||
name,
|
||||
position,
|
||||
&mix.known_song_ids,
|
||||
old.id
|
||||
)
|
||||
.execute(database)
|
||||
@@ -225,8 +226,8 @@ pub async fn build_mixes(
|
||||
let mix_id = Uuid::new_v4();
|
||||
sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO "cluster_mix_playlist" (id, rule_id, playlist_id, tags, name, position)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
INSERT INTO "cluster_mix_playlist" (id, rule_id, playlist_id, tags, name, position, known_song_ids)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
"#,
|
||||
mix_id,
|
||||
rule.id,
|
||||
@@ -234,6 +235,7 @@ pub async fn build_mixes(
|
||||
&mix.tags,
|
||||
name,
|
||||
position,
|
||||
&mix.known_song_ids,
|
||||
)
|
||||
.execute(database)
|
||||
.await?;
|
||||
|
||||
@@ -30,6 +30,8 @@ pub struct Mix {
|
||||
/// Library genres describing the mix, best first
|
||||
pub tags: Vec<String>,
|
||||
pub song_ids: Vec<String>,
|
||||
/// The songs in the mix that were played recently
|
||||
pub known_song_ids: Vec<String>,
|
||||
}
|
||||
|
||||
/// A track from the listening history
|
||||
@@ -209,6 +211,8 @@ pub async fn build_mix(
|
||||
}
|
||||
}
|
||||
|
||||
let known_song_ids: Vec<String> = selection.songs.iter().map(|s| s.id.clone()).collect();
|
||||
|
||||
// ---- discovery: weighted random sample of well-fitting songs ----
|
||||
// Efraimidis-Spirakis: sort by u^(1/w) to sample without replacement, weighted by w
|
||||
let mut ranked: Vec<(f64, &Track)> = pool
|
||||
@@ -257,6 +261,7 @@ pub async fn build_mix(
|
||||
.map(|(k, _)| library_genres[k].clone())
|
||||
.collect(),
|
||||
song_ids: chosen.into_iter().map(|s| s.id).collect(),
|
||||
known_song_ids,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -231,6 +231,7 @@ pub struct ClusterMixPlaylist {
|
||||
pub tags: Vec<String>,
|
||||
pub name: Option<String>,
|
||||
pub position: i32,
|
||||
pub known_song_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
||||
+11
@@ -82,6 +82,8 @@ struct MixDetail {
|
||||
#[serde(flatten)]
|
||||
summary: MixSummary,
|
||||
songs: Vec<Track>,
|
||||
/// Songs in `songs` the user played recently
|
||||
known_song_ids: Vec<String>,
|
||||
suggestions: Vec<MixSuggestion>,
|
||||
}
|
||||
|
||||
@@ -117,6 +119,14 @@ async fn mix(
|
||||
})?
|
||||
.entry;
|
||||
|
||||
let known_song_ids = sqlx::query_scalar!(
|
||||
r#"SELECT known_song_ids FROM "cluster_mix_playlist" WHERE id = $1"#,
|
||||
id
|
||||
)
|
||||
.fetch_one(pool.inner())
|
||||
.await
|
||||
.map_err(db_error)?;
|
||||
|
||||
let suggestions = sqlx::query_as!(
|
||||
MixSuggestion,
|
||||
r#"
|
||||
@@ -133,6 +143,7 @@ async fn mix(
|
||||
Ok(Json(MixDetail {
|
||||
summary,
|
||||
songs,
|
||||
known_song_ids,
|
||||
suggestions,
|
||||
}))
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user