diff --git a/README.md b/README.md index e7771bf..951163f 100644 --- a/README.md +++ b/README.md @@ -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 `/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 `/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 diff --git a/src/main/kotlin/win/taptap/musicmanager/api/ApiModels.kt b/src/main/kotlin/win/taptap/musicmanager/api/ApiModels.kt index a23fda4..fd6bbe9 100644 --- a/src/main/kotlin/win/taptap/musicmanager/api/ApiModels.kt +++ b/src/main/kotlin/win/taptap/musicmanager/api/ApiModels.kt @@ -99,6 +99,8 @@ data class MoodDto( val query: String? = null, val genres: List = 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 = 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 diff --git a/src/main/kotlin/win/taptap/musicmanager/api/MoodApi.kt b/src/main/kotlin/win/taptap/musicmanager/api/MoodApi.kt index 8fee9ce..08af3fc 100644 --- a/src/main/kotlin/win/taptap/musicmanager/api/MoodApi.kt +++ b/src/main/kotlin/win/taptap/musicmanager/api/MoodApi.kt @@ -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)) diff --git a/src/main/kotlin/win/taptap/musicmanager/db/MoodRepository.kt b/src/main/kotlin/win/taptap/musicmanager/db/MoodRepository.kt index 2f8e700..880b9b0 100644 --- a/src/main/kotlin/win/taptap/musicmanager/db/MoodRepository.kt +++ b/src/main/kotlin/win/taptap/musicmanager/db/MoodRepository.kt @@ -26,6 +26,7 @@ data class MoodRecord( val query: String?, val genres: List, 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, + 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], diff --git a/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt b/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt index 8ddcd50..b1513a9 100644 --- a/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt +++ b/src/main/kotlin/win/taptap/musicmanager/db/Tables.kt @@ -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() diff --git a/src/main/kotlin/win/taptap/musicmanager/download/YtDlpDownloader.kt b/src/main/kotlin/win/taptap/musicmanager/download/YtDlpDownloader.kt index dcb501b..b259bf2 100644 --- a/src/main/kotlin/win/taptap/musicmanager/download/YtDlpDownloader.kt +++ b/src/main/kotlin/win/taptap/musicmanager/download/YtDlpDownloader.kt @@ -24,6 +24,9 @@ class YtDlpDownloader( "--audio-quality", "0", "--embed-metadata", + "--embed-thumbnail", + "--convert-thumbnails", + "jpg", "--no-playlist", "--no-cache-dir", "--no-progress", diff --git a/src/main/kotlin/win/taptap/musicmanager/radio/RadioService.kt b/src/main/kotlin/win/taptap/musicmanager/radio/RadioService.kt index 239087b..5834d90 100644 --- a/src/main/kotlin/win/taptap/musicmanager/radio/RadioService.kt +++ b/src/main/kotlin/win/taptap/musicmanager/radio/RadioService.kt @@ -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>, + recommendationScored: List>, + limit: Int, + seedPercent: Int, + artistSpacing: Int = 2, + albumSpacing: Int = 3, + ): List { + val seeds = seedScored + .sortedByDescending { it.second } + .toMutableList() + val recommendations = recommendationScored + .sortedByDescending { it.second } + .toMutableList() + val percent = seedPercent.coerceIn(0, 100) + val picked = ArrayList(limit) + val artists = ArrayDeque() + val albums = ArrayDeque() + + 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>, + artists: ArrayDeque, + albums: ArrayDeque, + ): 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 diff --git a/src/main/resources/db/migration/V7__mood_mix.sql b/src/main/resources/db/migration/V7__mood_mix.sql new file mode 100644 index 0000000..9193bf9 --- /dev/null +++ b/src/main/resources/db/migration/V7__mood_mix.sql @@ -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; diff --git a/src/test/kotlin/win/taptap/musicmanager/api/ApiRoutesTest.kt b/src/test/kotlin/win/taptap/musicmanager/api/ApiRoutesTest.kt index 326ee95..5f282b3 100644 --- a/src/test/kotlin/win/taptap/musicmanager/api/ApiRoutesTest.kt +++ b/src/test/kotlin/win/taptap/musicmanager/api/ApiRoutesTest.kt @@ -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") { diff --git a/src/test/kotlin/win/taptap/musicmanager/discovery/DiscoveryServiceTest.kt b/src/test/kotlin/win/taptap/musicmanager/discovery/DiscoveryServiceTest.kt index 3936813..0890c98 100644 --- a/src/test/kotlin/win/taptap/musicmanager/discovery/DiscoveryServiceTest.kt +++ b/src/test/kotlin/win/taptap/musicmanager/discovery/DiscoveryServiceTest.kt @@ -101,6 +101,7 @@ class DiscoveryServiceTest { query = query, genres = genres, targetSize = 30, + seedPercent = 50, refreshHours = 24, ytEnabled = true, lastDiscoveryAt = null, diff --git a/src/test/kotlin/win/taptap/musicmanager/radio/RadioServiceTest.kt b/src/test/kotlin/win/taptap/musicmanager/radio/RadioServiceTest.kt index 2a0861b..ce5fb14 100644 --- a/src/test/kotlin/win/taptap/musicmanager/radio/RadioServiceTest.kt +++ b/src/test/kotlin/win/taptap/musicmanager/radio/RadioServiceTest.kt @@ -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",