feat: mix mood radio by seed percentage and embed download artwork
CI / chart (push) Successful in 3s
CI / chart-push (push) Successful in 5s
CI / test (push) Successful in 1m50s
CI / image (push) Successful in 3m16s

Moods now store a seedPercent (0-100, default 50). RadioService rolls that
share independently for every queued slot: heads picks from the seed songs,
tails from the generated recommendation pool. When one pool is empty the other
fills the batch, so a mood never stalls. The DTO exposes both seedPercent and
the derived recommendationPercent, and create/patch accept seedPercent.

Automatic YT downloads now embed the video thumbnail as MP3 cover art so the
scanner publishes a cover for newly imported tracks.

V7 adds moods.seed_percent.
This commit is contained in:
TapTap committed 2026-11-15 17:07:04 +00:00
1 parent dd7bbde84d
commit c75f2971b4
11 files changed
+146 -6

No files matched your search

+5 -3
View File
@@ -119,6 +119,7 @@ Passwords are read into memory at startup and never written to SQLite. In produc
A mood is a private collection owned by one user:
- **Seeds** are permanent anchors. Every seed is always eligible for the radio.
- **Seed mix** (`seedPercent`, 0–100) chooses how much of each batch comes from the seeds. The rest is filled from the generated recommendation pool (genres, artists, text matches and the rest of the library). Every slot rolls the percentage independently; when one pool is exhausted the other fills in. The default is 50/50.
- **Genres / free-text hint** widen the candidate pool.
- **Target size** is the desired batch and session size, not a hard playlist length.
- **Radio** is generated by the server for each playback session. It mixes seeds, related genres and artists, text matches, and the rest of the owner's music. Tracks started, finished or skipped in the last 7 days are skipped while the library is large enough, and artists/albums are spaced across the batch.
@@ -172,9 +173,10 @@ Song objects contain deterministic IDs (`sg-…`), album/artist names, duration,
### Moods
- `GET /moods`
- `POST /moods` — `{ name, description?, query?, genres[], targetSize, refreshHours, ytEnabled, seedSongIds[] }`
- `POST /moods` — `{ name, description?, query?, genres[], targetSize, refreshHours, ytEnabled, seedSongIds[], seedPercent? }`
- `seedPercent` is 0–100 (default 50); the mood DTO also reports `recommendationPercent = 100 - seedPercent`.
- `GET /moods/{id}` — mood, seeds and recommendations.
- `PATCH /moods/{id}` — partial settings update; `clearDescription` / `clearQuery` clear fields.
- `PATCH /moods/{id}` — partial settings update, including `seedPercent`; `clearDescription` / `clearQuery` clear fields.
- `DELETE /moods/{id}`
- `POST /moods/{id}/seeds` — `{ songId }`
- `DELETE /moods/{id}/seeds/{songId}`
@@ -184,7 +186,7 @@ Song objects contain deterministic IDs (`sg-…`), album/artist names, duration,
- `POST /moods/{id}/recommendations/{videoId}/accept` — accept; the library match becomes a seed immediately.
- `POST /moods/{id}/recommendations/{videoId}/reject` — reject; the candidate is not offered again.
Accepted recommendations without a library match are queued for download (`download.state` = `queued|downloading|done|failed` in the recommendation). The worker writes MP3s into `<music folder>/AudioManager Imports`, runs a scan, matches the new song, adds it as a seed and updates the recommendation.
Accepted recommendations without a library match are queued for download (`download.state` = `queued|downloading|done|failed` in the recommendation). The worker writes MP3s into `<music folder>/AudioManager Imports`, embeds the video thumbnail as cover art, runs a scan, matches the new song, adds it as a seed and updates the recommendation.
### Radio sessions
@@ -99,6 +99,8 @@ data class MoodDto(
val query: String? = null,
val genres: List<String> = emptyList(),
val targetSize: Int,
val seedPercent: Int,
val recommendationPercent: Int,
val refreshHours: Int,
val ytEnabled: Boolean,
val lastDiscoveryAt: String? = null,
@@ -116,6 +118,8 @@ fun MoodRecord.toDto(): MoodDto = MoodDto(
query = query,
genres = genres,
targetSize = targetSize,
seedPercent = seedPercent,
recommendationPercent = 100 - seedPercent,
refreshHours = refreshHours,
ytEnabled = ytEnabled,
lastDiscoveryAt = lastDiscoveryAt,
@@ -150,6 +154,8 @@ data class CreateMoodRequest(
val refreshHours: Int = 24,
val ytEnabled: Boolean = true,
val seedSongIds: List<String> = emptyList(),
/** Share of each batch that comes from the seed songs; the rest is recommended. */
val seedPercent: Int = 50,
)
@Serializable
@@ -163,6 +169,7 @@ data class UpdateMoodRequest(
val targetSize: Int? = null,
val refreshHours: Int? = null,
val ytEnabled: Boolean? = null,
val seedPercent: Int? = null,
)
@Serializable
@@ -68,6 +68,7 @@ fun Route.moodRoutes(
refreshHours = request.refreshHours,
ytEnabled = request.ytEnabled,
seedSongIds = seedIds,
seedPercent = request.seedPercent,
)
call.respond(HttpStatusCode.Created, detail(mood, user, library))
}
@@ -104,6 +105,7 @@ fun Route.moodRoutes(
targetSize = request.targetSize ?: mood.targetSize,
refreshHours = request.refreshHours ?: mood.refreshHours,
ytEnabled = request.ytEnabled ?: mood.ytEnabled,
seedPercent = request.seedPercent ?: mood.seedPercent,
) ?: notFound("Mood")
call.respond(detail(updated, user, library))
@@ -26,6 +26,7 @@ data class MoodRecord(
val query: String?,
val genres: List<String>,
val targetSize: Int,
val seedPercent: Int = 50,
val refreshHours: Int,
val ytEnabled: Boolean,
val lastDiscoveryAt: String?,
@@ -99,6 +100,7 @@ object MoodRepository {
refreshHours: Int,
ytEnabled: Boolean,
seedSongIds: List<String>,
seedPercent: Int = 50,
): MoodRecord = transaction {
val now = Instant.now().toString()
val id = IdGenerator.moodId(owner, name, now)
@@ -111,6 +113,7 @@ object MoodRepository {
it[MoodsTable.query] = query?.trim()?.takeIf(String::isNotEmpty)
it[MoodsTable.genres] = encodeGenres(genres)
it[MoodsTable.targetSize] = targetSize.coerceIn(5, 500)
it[MoodsTable.seedPercent] = seedPercent.coerceIn(0, 100)
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
it[MoodsTable.ytEnabled] = ytEnabled
it[createdAt] = now
@@ -134,6 +137,7 @@ object MoodRepository {
targetSize: Int,
refreshHours: Int,
ytEnabled: Boolean,
seedPercent: Int = 50,
): MoodRecord? = transaction {
val exists = MoodsTable.selectAll()
.where { (MoodsTable.id eq id) and (MoodsTable.owner eq owner) }
@@ -146,6 +150,7 @@ object MoodRepository {
it[MoodsTable.query] = query?.trim()?.takeIf(String::isNotEmpty)
it[MoodsTable.genres] = encodeGenres(genres)
it[MoodsTable.targetSize] = targetSize.coerceIn(5, 500)
it[MoodsTable.seedPercent] = seedPercent.coerceIn(0, 100)
it[MoodsTable.refreshHours] = refreshHours.coerceIn(1, 720)
it[MoodsTable.ytEnabled] = ytEnabled
it[changedAt] = Instant.now().toString()
@@ -430,6 +435,7 @@ object MoodRepository {
query = row[MoodsTable.query],
genres = decodeGenres(row[MoodsTable.genres]),
targetSize = row[MoodsTable.targetSize],
seedPercent = row[MoodsTable.seedPercent],
refreshHours = row[MoodsTable.refreshHours],
ytEnabled = row[MoodsTable.ytEnabled],
lastDiscoveryAt = row[MoodsTable.lastDiscoveryAt],
@@ -147,6 +147,7 @@ object MoodsTable : Table("moods") {
val query = text("query").nullable()
val genres = text("genres").default("[]")
val targetSize = integer("target_size").default(30)
val seedPercent = integer("seed_percent").default(50)
val refreshHours = integer("refresh_hours").default(24)
val ytEnabled = bool("yt_enabled").default(true)
val lastDiscoveryAt = varchar("last_discovery_at", 40).nullable()
@@ -24,6 +24,9 @@ class YtDlpDownloader(
"--audio-quality",
"0",
"--embed-metadata",
"--embed-thumbnail",
"--convert-thumbnails",
"jpg",
"--no-playlist",
"--no-cache-dir",
"--no-progress",
@@ -30,10 +30,11 @@ data class StartedSession(
* session are never repeated. The client asks for more whenever its buffer is
* low, so the queue is always generated with the latest signals.
*/
class RadioService {
class RadioService(
private val random: Random = Random.Default,
) {
private val log = LoggerFactory.getLogger(RadioService::class.java)
private val random = Random.Default
fun start(
mood: MoodRecord,
@@ -166,7 +167,14 @@ class RadioService {
)
}
val picks = pickDiverse(scored, limit)
val seedScored = scored.filter { (song, _) -> song.id in seedIds }
val recommendationScored = scored.filter { (song, _) -> song.id !in seedIds }
val picks = pickMixed(
seedScored = seedScored,
recommendationScored = recommendationScored,
limit = limit,
seedPercent = mood.seedPercent,
)
if (persist && sessionId != null && picks.isNotEmpty()) {
RadioRepository.append(sessionId, picks.map { it.id })
}
@@ -195,6 +203,60 @@ class RadioService {
return score
}
/**
* Picks a batch with the mood's requested seed share. Each slot rolls the
* percentage independently, so a 70% mood gets roughly seven seed tracks in
* ten. An exhausted pool falls back to the other one instead of stalling.
*/
internal fun pickMixed(
seedScored: List<Pair<SongRecord, Double>>,
recommendationScored: List<Pair<SongRecord, Double>>,
limit: Int,
seedPercent: Int,
artistSpacing: Int = 2,
albumSpacing: Int = 3,
): List<SongRecord> {
val seeds = seedScored
.sortedByDescending { it.second }
.toMutableList()
val recommendations = recommendationScored
.sortedByDescending { it.second }
.toMutableList()
val percent = seedPercent.coerceIn(0, 100)
val picked = ArrayList<SongRecord>(limit)
val artists = ArrayDeque<String>()
val albums = ArrayDeque<String>()
while (picked.size < limit && (seeds.isNotEmpty() || recommendations.isNotEmpty())) {
val preferSeed = when {
seeds.isEmpty() -> false
recommendations.isEmpty() -> true
else -> random.nextInt(100) < percent
}
val pool = if (preferSeed) seeds else recommendations
val song = pool.removeAt(diverseIndex(pool, artists, albums)).first
picked += song
artists.addLast(song.displayArtist)
if (artists.size > artistSpacing) artists.removeFirst()
albums.addLast(song.albumId)
if (albums.size > albumSpacing) albums.removeFirst()
}
return picked
}
private fun diverseIndex(
pool: List<Pair<SongRecord, Double>>,
artists: ArrayDeque<String>,
albums: ArrayDeque<String>,
): Int {
var index = pool.indexOfFirst { (song, _) ->
song.displayArtist !in artists && song.albumId !in albums
}
if (index < 0) index = pool.indexOfFirst { (song, _) -> song.displayArtist !in artists }
return if (index < 0) 0 else index
}
/**
* Picks the best remaining candidate while keeping artists and albums apart.
* An artist may return after [artistSpacing] other tracks, an album after
@@ -0,0 +1,3 @@
-- Share of each radio batch that should come from the mood's seed songs.
-- The rest is filled from the generated recommendation pool.
ALTER TABLE moods ADD COLUMN seed_percent INTEGER NOT NULL DEFAULT 50;
@@ -4,6 +4,7 @@ import io.ktor.client.HttpClient
import io.ktor.client.request.delete
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.patch
import io.ktor.client.request.post
import io.ktor.client.request.put
import io.ktor.client.request.setBody
@@ -153,6 +154,17 @@ class ApiRoutesTest {
val moodId = mood["mood"]!!.jsonObject.string("id")
assertEquals(1, mood["mood"]!!.jsonObject.int("seedCount"))
assertTrue(mood["seeds"]!!.jsonArray.isNotEmpty())
assertEquals(50, mood["mood"]!!.jsonObject.int("seedPercent"))
assertEquals(50, mood["mood"]!!.jsonObject.int("recommendationPercent"))
val mixed = client.patch("/api/v1/moods/$moodId") {
bearer(token)
contentType(ContentType.Application.Json)
setBody("""{"seedPercent":70}""")
}
val mixedMood = parse(mixed.bodyAsText())["mood"]!!.jsonObject
assertEquals(70, mixedMood.int("seedPercent"))
assertEquals(30, mixedMood.int("recommendationPercent"))
// Long-form can never be a mood seed.
val withLongform = client.post("/api/v1/moods") {
@@ -101,6 +101,7 @@ class DiscoveryServiceTest {
query = query,
genres = genres,
targetSize = 30,
seedPercent = 50,
refreshHours = 24,
ytEnabled = true,
lastDiscoveryAt = null,
@@ -1,5 +1,6 @@
package win.taptap.musicmanager.radio
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@@ -101,6 +102,46 @@ class RadioServiceTest {
assertTrue(service.pickDiverse(scored, limit = 2).first().id == "high")
}
@Test
fun `mood mix draws from seeds and recommendations in proportion`() {
val seeds = (1..20).map { song("seed-$it", artist = "Seed $it") }
val recommendations = (1..20).map { song("rec-$it", artist = "Rec $it") }
val seedScored = seeds.mapIndexed { index, song -> song to (10.0 - index * 0.1) }
val recommendationScored = recommendations.mapIndexed { index, song -> song to (9.0 - index * 0.1) }
val allSeeds = RadioService(Random(1)).pickMixed(
seedScored, recommendationScored, limit = 10, seedPercent = 100,
)
assertTrue(allSeeds.all { it.id.startsWith("seed-") })
val allRecommendations = RadioService(Random(1)).pickMixed(
seedScored, recommendationScored, limit = 10, seedPercent = 0,
)
assertTrue(allRecommendations.all { it.id.startsWith("rec-") })
val mixed = RadioService(Random(7)).pickMixed(
seedScored, recommendationScored, limit = 20, seedPercent = 50,
)
assertEquals(20, mixed.size)
assertEquals(20, mixed.map { it.id }.distinct().size)
assertTrue(mixed.any { it.id.startsWith("seed-") })
assertTrue(mixed.any { it.id.startsWith("rec-") })
}
@Test
fun `mood mix falls back when one pool is empty`() {
val seeds = listOf(song("only-seed"))
val picked = RadioService(Random(1)).pickMixed(
seedScored = seeds.map { it to 1.0 },
recommendationScored = emptyList(),
limit = 5,
seedPercent = 0,
)
assertEquals(listOf("only-seed"), picked.map { it.id })
}
private fun song(
id: String,
artist: String = "Artist $id",