A self hosted navidrome radio/dj front end with AI radio host.
  • Python 42.4%
  • Kotlin 30.4%
  • TypeScript 26.6%
  • Shell 0.2%
  • Dockerfile 0.2%
  • Other 0.1%
Find a file
2026-09-14 22:43:27 -04:00
android fix queue 2026-08-07 00:33:35 -04:00
backend start work on airtime 2026-09-14 22:43:27 -04:00
docs/screenshots add pictures to readme 2026-08-03 22:20:19 -04:00
frontend add listenbrainz functionality. 2026-08-05 19:38:19 -04:00
.env.example login and logout stuff 2026-08-04 01:23:52 -04:00
.gitignore work on dj to make them less suck ass 2026-08-01 03:05:45 -04:00
docker-compose.yml login and logout stuff 2026-08-04 01:23:52 -04:00
icon.png changes to skip weight and update readme 2026-07-20 12:57:29 -04:00
README.md fixes 2026-08-08 11:45:04 -04:00
soundtracks.jpg favs in stats and station fix 2026-08-05 01:54:08 -04:00

DJ — Self-Hosted AI Radio

A self-hosted web radio app that turns your Navidrome music library into a personalized AI-driven station. Pick a genre, start listening, and the app learns your taste over time — weighting songs you love higher and fading out tracks you dislike. Between songs, an AI voice host reads original DJ breaks: artist trivia, weather, what's coming next, genre commentary, and more.

Everything runs in two Docker containers on hardware you control. No cloud music service, no subscription beyond the (optional) Claude API for AI breaks.


Table of Contents

Getting started

Using it

Other clients

Running it

Reference


Features

  • Genre-based stations — pick any genre from your Navidrome library and the app builds a continuous queue weighted by your votes
  • Vote-to-train — Love / Like / Dislike / Skip buttons adjust how often each song recurs; dislike auto-skips immediately
  • Playlist management — add the current song to any existing Navidrome playlist, or create a new one, without leaving the player
  • Navidrome star sync — loving a song also stars it in Navidrome, so your ratings carry over to other clients
  • AI DJ breaks — every 3–5 songs, Claude Haiku writes a fresh spoken DJ break (song trivia, artist stories, weather, genre vibes, listener shoutouts) and Kokoro TTS reads it aloud
  • Rotating DJ personas — four DJs with distinct written personalities, speaking speeds, and preferred break styles; each works a shift of 5–8 breaks, then hands off on air to the next. A fifth, Mike, sits outside the rotation as the segment/news host
  • Scheduled segments — chart countdowns from your own listening, a three-day forecast, artist facts sourced from real biographies, and news read from your RSS feeds, each on its own cadence
  • Weather in breaks — optionally supply lat/lon and breaks reference the current conditions via Open-Meteo (no API key required)
  • Listening stats — a stats page with totals (songs played, time listened, artists heard), plus top songs / top artists / per-station leaderboards, and a per-song breakdown reachable from the now-playing screen; song rows can be loved or added to a playlist in place
  • Similarity-based artist stations — artist stations play the seed's neighbourhood rather than its whole genre, so picking Shinedown gets post-grunge rather than all of "Rock", and Garth Brooks and Morgan Wallen produce completely different stations despite both being Country
  • Saved artist stations — save a multi-artist station and relaunch it later; star favourites to pin them to the top of the station list
  • Play history — see the last 50 tracks played with timestamps
  • Near-gapless playback — two-audio-element ping-pong with 20-second prefetch eliminates silence between songs
  • All config in the UI — Navidrome URL/credentials, Claude API key, TTS voice, break frequency, and station name are all stored in SQLite and editable from a settings panel; no .env file needed for secrets
  • Three clients, one history — the web player, a native Android app, and sonic-tui in the terminal all talk to the same backend, so votes, stats and play history are shared wherever you listen
  • Fully self-hosted — Docker Compose, two containers, one named volume

Architecture

browser · Android app · sonic-tui (terminal)
  │
  ├── GET /        → Nginx (frontend container, port 3000)
  │     React + TypeScript + Vite + Tailwind CSS
  │
  └── /api/*       → FastAPI (backend container, port 8000)
        │
        ├── SQLite (vote history, play history, settings, genre cache, saved stations)
        ├── Navidrome / OpenSubsonic REST API  ← your music library
        ├── Kokoro TTS (ONNX, CPU, ~310MB model)
        ├── Claude Haiku API                   ← optional, for DJ breaks
        └── Open-Meteo API                     ← optional, for weather in breaks

Key design decisions

Choice Reason
SQLite via aiosqlite Keeps the stack simple; no separate DB container needed
Kokoro ONNX TTS CPU-friendly (~310MB), fully local, no API cost
Claude Haiku Cheapest model that writes convincingly human-sounding DJ copy; ~$0.001/break
Settings in DB, not .env First-run setup flow in the browser; secrets never appear in shell history or compose files
Audio + cover art proxied through backend Navidrome credentials stay server-side; browser never sees them
Ping-pong audio elements Near-gapless transitions without a streaming server

Prerequisites

  • Docker and Docker Compose (V2 syntax — docker compose)
  • A running Navidrome instance (v0.49+ / OpenSubsonic compatible)
  • Optional: an Anthropic API key for AI DJ breaks

Quick Start

1. Clone the repo

git clone <repo-url> dj
cd dj

2. Build and start

docker compose up --build -d

The first build takes a while — the backend image installs PyTorch (CPU build) and pre-downloads the Kokoro model weights (~310 MB). Subsequent builds are fast thanks to layer caching.

Low-power hardware note: The RUN python -c "from kokoro import KPipeline; ..." step initializes PyTorch on the CPU and can take 30+ minutes on ARM single-board computers or older VPS instances. If this happens, build on a faster machine and push the image, or comment out that line (the model will download on first break, adding a delay).

3. Open the app

Navigate to http://your-server:3000. You'll see a setup form.

4. Connect Navidrome

Enter your Navidrome server URL, username, and password. The app will ping Navidrome to verify the credentials before saving them. You're listening within seconds.


First-Run Setup

The setup screen only asks for Navidrome credentials — the minimum needed to start playing music. Everything else is optional and can be added later from the Settings panel (⚙ in the top-right corner).

┌─────────────────────────────────────┐
│  Navidrome URL                      │
│  https://music.example.com          │
│                                     │
│  Username  ──────────────────────── │
│  Password  ──────────────────────── │
│                                     │
│         [ Connect ]                 │
└─────────────────────────────────────┘

Settings Reference

Open the ⚙ Settings panel to configure any of the following. Changes take effect immediately — no restart required.

Music Server

Field Description
Navidrome URL Base URL of your Navidrome instance (e.g. https://music.example.com)
Username Navidrome username
Password Leave blank to keep the existing password; type a new one to change it

AI DJ

Requires an Anthropic API key. Sign up at console.anthropic.com — it's pay-as-you-go, no subscription needed. At typical usage (~20 breaks/day), cost is under $1/month using Haiku.

Field Description
Anthropic API Key Leave blank to keep existing; clears to disable AI breaks
Voice Kokoro TTS voice preset (11 options: American/British, male/female)
Speed TTS speech rate multiplier (0.8 = slower, 1.2 = faster; default 0.95)

Available voices:

Value Label
af_sky Sky (American female) — default
af_heart Heart (American female)
af_bella Bella (American female)
af_sarah Sarah (American female)
af_nicole Nicole (American female)
am_adam Adam (American male)
am_michael Michael (American male)
bf_emma Emma (British female)
bf_isabella Isabella (British female)
bm_george George (British male)
bm_lewis Lewis (British male)

DJ Breaks

Field Description
Break every (min) Minimum songs between breaks (default 3)
Break every (max) Maximum songs between breaks (default 5)

The actual interval is random within this range — so a 3–5 setting means a break every 3, 4, or 5 songs. Increase the range for a more music-forward experience.

Rotation

Field Description
Artist repeat gap Songs that must pass before the same artist repeats. Genre stations only — artist stations are meant to revisit their seeds
Artist similarity source Auto (default — Last.fm, falling back to ListenBrainz), Last.fm only (needs a Last.fm key in Navidrome), or ListenBrainz only (no key, real co-listen scores). See Artist Similarity

Weather

Used to add real weather context to DJ break scripts. Powered by Open-Meteo — no API key required.

Field Description
Latitude Decimal latitude (e.g. 40.7128)
Longitude Decimal longitude (e.g. -74.0060)

Leave both blank to disable weather in breaks.

Station

Field Description
Station Name Displayed in the header and referenced in DJ breaks

Using the Web Player

Picking a Station

Picking a station on the web

The home screen shows a Spotify-style genre grid — colored tiles with album art and genre names. Click any tile to start listening. An Artist Station banner at the top lets you search for one or more artists to seed a personalized station.

In the artist search, Save stores that set of artists as a reusable station without starting it; Start Station plays it immediately. Saved stations appear in a Saved Stations section above the genre grid, where you can star a favourite (pins it to the top) or delete it.

Click the search icon (🔍) in the header to filter genres by name, the chart icon for your listening stats, or ⚙ for settings.

Now Playing Screen

Now Playing on the web

Clicking a genre opens the full-screen player, which slides up over the genre grid. The player shows:

  • Blurred album art background
  • Large album art card with break script overlay during DJ breaks
  • Track title and artist · album
  • Progress bar with elapsed / total time
  • Transport row: Stop | Play/Pause | Skip
  • Actions row: Dislike · Like · Love · Add to Playlist · Queue · Artist Station · Song Stats · Wrong Genre

Click the ↓ arrow to collapse back to the genre grid (music keeps playing). A mini player bar appears at the bottom of the genre screen while a station is active, with album art, title/artist, play/pause, and skip.

Queue

Tap the Queue button (♫) in the actions row to open the queue panel, which slides up inside the player view. It shows:

  • Up Next — the prefetched next song
  • History — the last 50 tracks played

Each item has a three-dot menu with Love, Add to Playlist, and Wrong Genre actions.

"Up Next" is a promise, so the prefetch and the player must move together. /api/next consumes a segment from the server queue — it isn't a peek. So a prefetch that gets displayed but never queued for playback strands that song completely: it's gone from the server and it never plays here. On Android that's exactly what happened, because the prefetch assigned the "up next" slot unconditionally while only enqueueing the audio when ExoPlayer had room (mediaItemCount < 2). When it didn't, the panel named a song the player was never going to reach, ExoPlayer advanced to whatever it already held, and the transition handler then relabelled that audio with the stranded song's title — so both "up next" and now-playing were wrong. The fetch is now skipped entirely when the player is full, and the display slot and the media item are assigned as one step. fetchAndPlay() (first play, queue ran dry, skip with nothing prefetched) also clears the player first rather than appending, which was the other way the two could fall out of step.

Vote Buttons

Button Effect
❤ Love 3× weight in future queues; stars the song in Navidrome
👍 Like 1.5× weight
👎 Dislike 0.1× weight; immediately skips to the next song
⏭ Skip 0.8× per skip (compounds — skipping the same song repeatedly fades it out gradually); invalidates any queued DJ break so the next one reflects current history
⚑ Wrong Genre Report the song as miscategorized; opens a genre picker so you can select the correct genre; skips immediately
+ Playlist Add the current song to an existing Navidrome playlist or create a new one

Votes persist in SQLite and affect song selection across sessions. The active vote is highlighted after you click it.

Song weighting details

Every candidate starts at 1.0 and gets multiplied by each factor that applies. Nothing ever reaches zero — there's a 0.05 floor — so a suppressed song is unlikely rather than impossible, and the queue can never starve.

Factor Multiplier
Love / Like / Dislike 3.0× / 1.5× / 0.1× — global, see below
Skip 0.8× per skip, compounding — 1 skip 0.80×, 5 skips ≈ 0.33×, 10 ≈ 0.11×
Seed artist of the current station 2.0×
Similarity closeness (artist stations) 0.3× – 3.0× by distance from the seeds; 0.05× for anything that leaked in from the genre fallback
Collaboration credit ("A & B", "A • B") 0.25× — collabs are their own SQL partition and otherwise flood collab-heavy genres
Multi-artist compilation 0.2× — every track has a different credit, so nothing else suppresses them

Two independent recency decays. Song-level stops the same track recurring; artist-level stops one act dominating:

Time since last play Song decay Artist decay (genre stn) Artist decay (artist stn)
< 30 min 0.05× 0.05× 0.5×
< 1 hour 0.05× 0.05× 0.8×
< 2 hours 0.30× 0.35× 0.8×
< 4 hours 0.30× 0.35× 1.0×
< 12 hours 0.50× 0.7× 1.0×
< 24 hours 0.65× 0.7× 1.0×
< 3 days 0.80× 1.0× 1.0×
< 1 week 0.90× 1.0× 1.0×

The song decay used to stop at 24 hours, so a track heard yesterday was back at full weight today — which on a small artist-station pool means hearing it every day or two. It now tapers out over a week.

Artist stations deliberately behave differently. They exist to revisit the artists you seeded, so the hard artist-repeat gap is switched off entirely there and the artist-recency decay is much gentler. At genre-station strength (0.05× for an hour) that decay would out-punish even a 3× closeness boost, and a distant neighbour would consistently beat the artist you actually asked for — the station would drift away from its own premise. Song-level decay stays harsh on every station, because a repeated track is the repeat that grates.

Compilations lose to the real album. If a track exists in the library twice — on the artist's own album and again on some 00s Country compilation — those are two catalog rows with different IDs, and nothing tied them together: both were candidates, the compilation copy won about half the time, and neither the repeat block nor the recency decay recognised them as the same song, so it could come back round the next day off the other copy. Selection now collapses candidates by recording (title + artist), always keeping the non-compilation copy, and both the repeat block and song recency key on that same identity. A compilation track is only ever served when it's the only copy you own.

Detecting a compilation happens two ways: a catalog-wide scan for albums carrying 5+ distinct song artists, plus the albumArtist tag (Various, VA, Original Soundtrack, …). Two things about that scan are worth knowing:

  • It's catalog-wide and survives a station change. It used to be computed per-genre inside the genre refill only, which meant artist stations ran with an empty set and applied no compilation penalty at all — the reason a Garth Brooks station would happily serve a track off 00s Country.
  • It groups by (album, albumArtist), not by album title alone. Dozens of artists each have an album called Greatest Hits; grouping on the title alone counts them as one 50-artist album and flags every one of them as a compilation. Albums with no albumArtist tag still share a group and can still collide that way.

Votes, skips and recency are global, not scoped to the station where they happened — liking a song is a statement about the song, not about where you were standing when you said it, so a heart given on an artist station counts on the genre station too. (For votes the old scoping was doubly wrong: song_votes is keyed on song_id alone, so exactly one vote row exists per song, and filtering it by station simply hid the only vote there was.)

Hard blocks, applied before weighting:

  • Songs already queued or in retained history are excluded outright on every station — soft decay alone wasn't enough on a small artist-station pool. A final fallback pass allows a repeat only when the station has genuinely nothing else left, since silence is worse.
  • Artists heard within the repeat gap are blocked on genre stations only. The gap is the Settings slider, clamped to at most half the artists available so a large value over a small pool can't block everything and quietly behave like no gap at all.

DJ Breaks

After a random number of songs (configured min–max), the audio smoothly transitions to a short spoken DJ break. The break is pre-generated in the background so there's no delay.

Break types rotate randomly:

  • Song trivia — a surprising fact about a specific song or album just played
  • Artist story — a brief anecdote about one of the artists
  • Weather & time — current conditions woven into what's coming next
  • Coming up — anticipation-building intro for the next track
  • Genre vibe — evocative, non-literal commentary on the feel of the genre
  • Listener shoutout — warm, direct acknowledgment of the listener

When you skip a song, the pre-generated break is discarded and a new one is scheduled — so it won't reference tracks you didn't actually hear.

What the DJ actually knows

Breaks used to receive only song titles, a genre label and the weather. Asked to be "specific" with nothing specific available, the DJ manufactured atmosphere — inventing a listener in a kitchen at 3am, or observing that a song "just sits in the quiet part". That's a data-starvation failure, not a tone failure, and no amount of prompt scolding fixes it.

backend/app/dj_facts.py assembles context this app has that a broadcast DJ never could — all of it read from real listening history, so the DJ can be concrete and personal without inventing anything:

  • the station's seed artists (an artist station previously reached the DJ as just "Country")
  • album and year for the upcoming track
  • how many times the listener has played it, and when they last heard it
  • whether it has never been played before — a genuinely good hook
  • whether they loved or liked it, and total plays for that artist
  • whether this is the first time that artist has come up on this station — a hook that works on plain genre stations too, where there are no seed artists to relate to
  • how the incoming artist relates to the station's seeds, from the similarity graph, including why they're connected

Genre stations get all of the above except the seed-relationship line, since the history facts aren't station-specific.

Where the "why" comes from: Last.fm supplies similarity edges but no explanation, and "sounds similar" isn't something a DJ can say on air. dj.describe_artist_connections() annotates them ("both defined the early-90s neotraditional sound"), cached in artist_similarity.reason. It's deliberately a filter over a supplied candidate list rather than an open-ended "who is similar to X", so the model can only annotate artists already known to be neighbours and cannot invent one — and it's told to omit anything it isn't confident about, because a wrong reason spoken on air is worse than no reason. It runs as a background task after a station starts, never in the request path, so station start stays instant; the first break or two simply go without a reason.

Facts are omitted rather than guessed when unknown, so the prompt never carries something the DJ could contradict, and fact-gathering failures are swallowed — a break with no facts still beats no break.

Two prompt rules backstop it: every break must use at least one supplied concrete detail (brevity is explicitly preferred over impressionistic filler), and weather may only be referenced when weather data was supplied and matches it — reflexive sign-offs like "stay warm" are banned outright, after Sarah wished a listener warmth at 80°F.

Why the scripts avoid dashes

Kokoro inserts a prosodic pause at essentially every punctuation mark, so heavily punctuated copy — which reads fine on the page — comes out stilted and stop-start aloud. Em-dashes and ellipses are the worst offenders, each landing like a full stop mid-clause.

Most of that was self-inflicted: Sarah's character sheet used to instruct her to "trail off — a dash or an ellipsis instead of finishing a thought," and the break-style prompts were themselves full of em-dashes. Both are fixed, and there's a global rule asking for flowing sentences with no dashes, ellipses or parenthetical asides.

tts._normalize_for_speech() is the safety net for anything that slips through: dashes and ellipses become commas, parentheses and smart quotes are dropped, and Navidrome's • multi-artist separator becomes "and" (otherwise it's either read aloud or lands as a hard stop in the middle of an artist's name). It then cleans up after itself — floating commas, doubled commas, and sentences left ending on a comma are all further sources of dead air.

Some residual pausing is simply how the model renders punctuation, and no amount of cleanup removes a comma that genuinely belongs there.

Segments

Alongside ordinary between-song patter the station runs scheduled segments — chart countdowns, the forecast, news. They all share one mechanism (backend/app/segments.py): fetch real content, hand it to a DJ, then stay quiet for a while. Adding another source is a registry entry plus a fetch function, not new plumbing.

Segment Read by Source Cadence
Song / artist countdown DJ on duty Your own play history, last 7 days once a day each
Station rundown DJ on duty Play history every other day
Artist fact DJ on duty Last.fm biography via getArtistInfo2 up to 6/day
Three-day forecast Mike Open-Meteo (free, no key) up to 3/day
News & feeds Mike Your RSS/Atom feeds up to 5/day, only when there's something new

Mike is the segment host and is deliberately not in the DJ rotation — he never does music patter. The conceit is a news desk breaking into the music, which is why his register is public-radio newsreader rather than radio-personality. Music trivia stays with whoever is on shift, so a song fact doesn't yank the listener out of the current voice mid-set.

Cadence lives in the database, not memory, so a restart can't reset the clock and let the same countdown fire twice. Each segment declares a minimum gap and a daily cap, and simply doesn't air when it has nothing worth saying — a chart won't run until there's a real week of listening behind it, and the news segment stays silent unless a feed has genuinely new entries.

Artist facts are sourced, not recalled. Asking a model for trivia invites invention — the exact failure this project kept hitting. The bio comes from Last.fm (cached, misses cached too) and the DJ's job is condensing supplied text, which is the safe use.

Feeds are configured in Settings → Content. Any RSS or Atom URL works; Reddit is just a feed (…/r/name/top/.rss?t=day) rather than a separate integration, since their JSON API now wants OAuth and blocks datacenter IPs. Adding a feed validates it immediately and marks the current contents as read, so the first airing is genuinely new items rather than a backlog dump.

DJ shifts

Four DJs (Sarah, Sky, Adam, Bella) rotate through shifts — Mike is excluded, since he only reads segments. Each has a written character sheet — speech patterns, example lines, and an explicit list of things they'd never say — plus their own Kokoro voice, base speaking speed, and a preferred subset of break styles, so the structure of what they talk about reinforces the personality, not just the wording.

A shift is measured in breaks actually delivered, not songs played: each DJ does 5–8 spoken breaks (starting with a self-introduction), then signs off and hands over to the next DJ on air. Counting breaks rather than songs matters — with breaks firing every 3–5 songs, a shift measured in songs could end after only one or two utterances, and skipped songs would burn shift time the DJ never got to use. Breaks discarded by a skip or genre change cost the current DJ nothing.

The roster lives in DJ_ROSTER in backend/app/dj.py; shift length is _DJ_SHIFT_MIN/_DJ_SHIFT_MAX in backend/app/main.py.


Artist Similarity

Genre alone is far too coarse for a station: "Rock" spans sixty years, and Morgan Wallen and Garth Brooks are both "Country" while sharing almost no audience. Artist stations therefore build a neighbourhood around their seed artists instead of playing the seed's genre.

Edges come from one of two providers, chosen in Settings → Artist similarity source. Both are real crowd co-listening data, not heuristics. They're cached in artist_similarity keyed by source, so the two coexist — switching providers wipes nothing and you can flip back and forth to compare. artist_similarity_fetched records that a provider was asked even when the answer was empty, so artists with genuinely no neighbours aren't re-fetched on every station start.

Source Key needed Scores Library-aware
Last.fm, via Navidrome's getArtistInfo2 yes — a Last.fm key configured in Navidrome no, ordering only yes — returns only artists you own
ListenBrainz, via the similar-artists dataset none yes — real co-listen counts no
Auto (default) none either either

ListenBrainz needs no API key anywhere and returns measured listener overlap, so closeness is real rather than inferred from rank position. Two consequences worth knowing:

  • It's keyed by MusicBrainz ID, not by name, so every artist needs resolving first. Navidrome is asked first (free, no rate limit, and an exact ID from file tags); failing that, MusicBrainz's search API, which is rate-limited to one lookup per second and matches on exact name only — a fuzzy match is how you end up building a station around "Garth Brooks Tribute". Results are cached permanently in artist_mbid, misses included, since an MBID never changes.
  • Its scores are absolute co-listen counts, so they track how popular the seed is rather than how close the neighbour is — Alter Bridge's top neighbour scores 1637 where Lorrie Morgan's scores 122. They're normalised per seed, otherwise a popular seed would swamp an obscure one in a multi-artist station.
  • It knows nothing about your library, so more of what it returns is unplayable here and gets dropped by playable_pool(). That's why it keeps 100 neighbours per artist where the Last.fm path keeps 40.

Auto is the default, because plain Last.fm fails silently: with no Last.fm key configured in Navidrome, getArtistInfo2 returns nothing, every artist station quietly degrades into a genre station, and nothing anywhere says why. Auto is identical to Last.fm whenever Last.fm can answer — same edges, no MBID lookup, no extra request — and only reaches for ListenBrainz where the alternative was nothing at all.

Auto still keeps Last.fm as the primary source rather than preferring ListenBrainz, because Last.fm's list is pre-filtered to artists you own: 40 Last.fm neighbours are 40 playable ones, where 100 ListenBrainz neighbours might contain a handful you have. On a large library ListenBrainz alone may well be better — run the diagnose endpoint below and compare similar_with_songs_in_catalog for each before switching.

The pool is weighted by distance — seeds 1.0, first-degree neighbours next, second-degree well below — and fed to the playlist scorer as a multiplier rather than a hard filter, so an unrelated artist is heavily suppressed but the queue never starves. Genre survives only as a fallback pool for when a seed has too few library neighbours to fill a queue.

How much of the station is the artist you picked? About 15%, and getting there needed two caps lifted — weighting alone couldn't do it:

Old Now
Songs each artist contributes per refill 3, flat 15 seed · 4 close neighbour · 2 distant
Times one artist may appear in a 15–20 song batch 1 3 for seeds, 1 for everyone else
Measured seed share of a simulated 200-song station 5% 14%

A flat quota looks fair and isn't. A seed with 80 tracks in the library offered three of them per refill; so did a second-degree neighbour who owns exactly one song. With ~60 neighbours in a pool that put the seed at roughly 3% of candidates — weighted 3× inside a pool it had barely been let into — while the batch rule capped it at one appearance per 15–20 songs regardless. A Garth Brooks station played very little Garth Brooks.

The same flat quota also drove track repeats: an artist owning one song contributed that identical song to every refill, where the seed contributed three freshly-randomised ones out of eighty. Sparse neighbours looped while the deep seed rotated — exactly backwards. Genre stations are unaffected; both rules only change behaviour when artist_weights is set. The dials are _SEED_POOL_QUOTA and _SEED_BATCH_SLOTS at the top of backend/app/playlist.py; the batch slots have the sharper effect.

Station range (the tightness parameter, 0 = wander … 1 = stay close) is exposed in the artist-station picker on both clients as Close / Balanced / Adventurous.

Two things worth knowing if this ever misbehaves:

  • On the Last.fm source it depends on a Last.fm API key being configured in Navidrome. Without one, getArtistInfo2 returns nothing and stations quietly fall back to genre — switch the source to Auto or ListenBrainz and the problem goes away without configuring anything. GET /api/similar/diagnose reports whether the source is live and — more importantly — how many of the returned neighbours you actually own, which is the number that decides viability. It deliberately bypasses the cache, so it is slow: up to five network round trips per artist, several of them Navidrome calling out to Last.fm. Artists are checked concurrently and each is bounded by ?timeout= (20s default) so it always answers; narrow it further with ?artist=Name or ?lb=0. A diagnose request that itself crawls is a finding, not a glitch — it means a provider isn't answering promptly.
  • Artist resolution is deliberately not "first search hit". Navidrome's search3 surfaces phantom 0-album collaboration entries ahead of real artists ("Johnny Cash" → "Johnny Cash, Sheryl Crow"; "John Anderson" → the real artist ranked fifth), and those have no Last.fm data, so the naive lookup returns zero neighbours and looks like "similarity unavailable". resolve_artist() prefers an exact name match, then the most albums.

Stats

Stats page on the web

The stats page (📊 in the station picker header, or the stats icon on the now-playing screen for a single song) is built entirely from data the app already records — no extra tracking.

  • Overview — total songs played, time listened, unique songs/artists/stations, loved count, skips, and your busiest listening hour
  • Charts — a Listening activity area chart (plays per day, last 30 days) and a When you listen bar chart (plays by hour of day). Both are single-series, so they use one accent colour: bar height already encodes magnitude and colouring by value too would double-encode it. Days and hours with no plays are returned as real zeros rather than omitted, so neither axis compresses gaps. The web charts have a hover crosshair/tooltip; on both platforms the scale max and the peak are labelled directly, so no value is reachable only by hovering
  • Top songs / artists — leaderboards with play counts and last-played times; tap a song for its full breakdown
  • Stations — per-station listening time, play count, most-played artist, representative album art, and an inline meter showing each station's share of total listening time
  • Most skipped — the songs you bail on most, each shown alongside its play count so you can see the ratio. Sourced from the skip log rather than play history, so a song you skip instantly still appears (with 0 plays) — those are the ones worth disliking outright or filtering
  • Per-song — play count, your all-time ranking for it, completed vs. skipped plays, first/last played, the station it last played on, and total plays for that artist. Station is read from the play log, not from the song's genre tag: an album's tag describes the release, so a country single on a compilation tagged Soundtracks would otherwise be reported as having played on a Soundtracks station it was never served from
  • Acting on what you see — every song row on the Top songs, Most skipped and per-song views carries a ❤ and an add to playlist button, so a track you spot in the leaderboards can be loved or filed away without waiting for it to come round again. Loving from here does exactly what the heart on the now-playing screen does: stars the song in Navidrome and gives it a 3× weight in selection

Acting on a song after a rescan: the heart and playlist buttons need an ID Navidrome still recognises, which the song_id in an old play-history row may not be (see below). The stats endpoints therefore return a separate catalog_id — the resolved, current ID — and the UI acts on that. When a song has left the library entirely there is no current ID, so both buttons are shown dimmed rather than failing silently against a dead ID.

How listening time is measured: only songs played to completion count toward time. /api/completed marks a play complete when the song ends naturally; a skipped song still counts as a play but contributes no time, since the app never learns how far you actually got. Plays recorded before this tracking existed are all treated as complete.

Surviving a Navidrome rescan: Navidrome regenerates its song IDs on a library rescan or version upgrade, which orphans every existing row in play_history — joining those rows to the rebuilt catalog by ID yields nothing, so historical plays lose their artwork and their duration (silently zeroing their listening time). Because play_history also stores title and artist, the stats queries fall back to matching on those when an ID no longer resolves, so history survives a rescan. The fallback is a LIMIT 1 scalar subquery rather than an OR in the join — an OR join can match the same title/artist across several albums, multiplying rows and inflating play counts. idx_catalog_title_artist backs the lookup, and the catalog rebuild recreates that index when it swaps the table in.


Android App

A native Android client is included in the android/ directory. It connects to the same backend as the web app.

Pick a Station Now Playing Your Stats
Android station picker Android now playing Android stats

Features

  • Immersive dark player — album art fills the card edge-to-edge, with the cover ultra-blurred behind the whole screen for depth; background crossfades between songs so there's no black flash on track change
  • Swipe left on the album art to skip to the next song; swipe down anywhere on the player to collapse to the mini player
  • Two-row controls: transport row (Stop / Play-Pause / Skip) above a voting row (Dislike / Like / Love / Add to Playlist / Queue / Song Stats / Wrong Genre)
  • Mini player — a compact bar docks at the bottom of the genre screen while music is playing, with album art, track info, play/pause, and skip; tap or swipe up to expand back to the full player
  • Queue — swipe up on the Now Playing screen to reveal the queue panel (Up Next + History); swipe down or tap ↓ to return; each queue item has a three-dot menu for Love, Add to Playlist, and Wrong Genre
  • Add the current song to any Navidrome playlist or create a new one without leaving the player
  • Genre picker — 2-column Spotify-style grid of colored tiles; each tile shows a genre icon instantly and crossfades to a real album cover once loaded; covers are disk-cached so revisits are instant; tap the 🔍 icon in the header to filter by name
  • Artist Station — search for one or more artists to seed a personalized station; Save keeps it for later
  • Saved Stations — saved artist stations appear under the Artist Station banner, favourites first; tap to play, star to pin, ✕ to delete
  • Stats — tap the chart icon in the genre-picker header for overview totals and top songs / artists / stations / most-skipped; the chart icon in the player's action row opens stats for the current song. Song rows and the per-song sheet both carry ❤ and add to playlist buttons
  • Wrong genre reporting with a searchable genre picker
  • Background playback via a foreground MediaSessionService; controls appear in the notification shade and on lock screen

Setup

  1. Open the app — the first-run screen asks for your server URL, Navidrome URL, username, and password.
  2. After connecting, pick a genre or artist station and start listening.
  3. Settings are stored on-device; the server URL can be changed via the ⚙ button on the genre picker screen.

Building

Open android/ in Android Studio, or build from the command line:

cd android
./gradlew assembleDebug

The resulting APK is at app/build/outputs/apk/debug/app-debug.apk.


Terminal Client (sonic-tui)

sonic-tui is a terminal music player for Navidrome that can also drive this backend — so the same library is reachable from the browser, an Android phone, and a TUI, all sharing one set of votes, stats and play history.

Point it at this server by adding a dj: section to its config:

dj:
  url: "https://radio.example.com"
  password_command: "pass show dj-radio"   # or password: "..."

A DJ page appears alongside its own Queue/Artists/Albums pages: pick a station and the server takes over the rotation, breaks included. Love, like, dislike, skip and add-to-playlist all act on the playing track and feed back here exactly as the web and Android clients do.

Two things it does differently, both forced by it being a terminal:

  • No "up next". /api/next consumes — the segment it returns is gone from the queue — and there's no read-only endpoint exposing what's upcoming. Rather than fetch a segment it might not play (which would lose the track), it shows recently-played from /api/history instead.
  • Breaks aren't tracks. With no album art panel to fill during a break, it renders the script itself where the cover normally sits, which is the only place the full text is readable in any client.

Its audio goes through mpv, which has its own HTTP stack, so the session cookie is passed explicitly — worth knowing if you write another client, since the symptom of getting that wrong is an API that works perfectly while playback 401s.


Docker Compose Reference

services:
  backend:
    build: ./backend
    ports:
      - "8000:8000"
    volumes:
      - dj_data:/data          # SQLite DB and generated break audio
    environment:
      - DB_PATH=/data/dj.db
      - BREAKS_DIR=/data/breaks
      - HF_HOME=/app/.cache/huggingface
      - DJ_API_KEY=${DJ_API_KEY:-}   # optional — see "Exposing this publicly" below

  frontend:
    build: ./frontend
    ports:
      - "3000:3000"
    depends_on:
      - backend

volumes:
  dj_data:

Environment variables are path overrides plus one optional shared secret (DJ_API_KEY). All other secrets (Navidrome password, Anthropic key) live in the dj_data SQLite volume, never in compose files or shell environments.

To put the frontend behind a reverse proxy (Nginx, Caddy, Traefik), proxy requests to port 3000. The frontend already proxies /api/* calls to the backend internally.


Reverse Proxy Example (Nginx)

server {
    listen 443 ssl;
    server_name radio.example.com;

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

The frontend Nginx config already handles /api/ proxying to the backend container, so no additional location block is needed for the API.

Exposing this publicly (Cloudflare Tunnel, etc.)

Set a password the first time you open the app. Until you do, the instance is completely open — including audio streaming, so anyone with the URL can play your library. A fresh install shows a "set a password" screen rather than letting you skip past it, and the backend logs a loud warning while unclaimed.

There is no password in .env. It lives hashed in the database like every other secret here, and is changed from Settings — no redeploy.

Design notes, because several obvious approaches don't work:

  • Sessions are HttpOnly cookies, not bearer tokens. The endpoints most worth protecting are the media GETs (/api/audio/song/…, /api/cover/…), and those are fetched by <audio src>, <img src> and ExoPlayer — none of which can attach an Authorization header. A header-only scheme leaves the actual music wide open while looking secure. Cookies are sent automatically by all three. (This is why DJ_API_KEY, which deliberately exempted GETs, was never sufficient on its own.)
  • The password is a salted PBKDF2-HMAC-SHA256 hash (240k iterations, stdlib only). A plain-text env var is exposed by any leaked backup; a hash isn't. It is stripped from /api/settings responses entirely rather than masked.
  • Tokens are stateless HMACs keyed off the stored hash — one user means no session table to maintain, and changing the password invalidates every existing session for free.
  • /api/auth/set-password is open only while unclaimed. Once a password exists it requires a live session or the current password, so nobody can take over a running instance.
  • On Android, three separate HTTP stacks talk to the backend (Retrofit, Coil for artwork, ExoPlayer for audio) and none of them share a cookie store, so each is handed the session independently. Miss one and the symptom is oddly specific: the API works but artwork or playback 401s.
  • DJ_API_KEY still works as an alternative credential for scripts, sent as X-API-Key.

Forgot the password? There's no email reset for a single-user app. Clear it directly and the app returns to the claim screen:

docker compose exec backend python3 -c "import sqlite3; d=sqlite3.connect('/data/dj.db'); d.execute(\"DELETE FROM app_settings WHERE key='password_hash'\"); d.commit()"

For defence in depth you can additionally put Cloudflare Access in front of the tunnel, which blocks unauthenticated traffic at the edge before it reaches the app. Note the Android client can't do browser SSO, so it would need a service token.


Updating

docker compose pull   # if using pre-built images
docker compose up --build -d

The dj_data volume persists across rebuilds — your votes, history, and settings are preserved. Schema migrations run automatically at startup.


Tech Stack

Backend

Component Version Purpose
Python 3.12 Runtime
FastAPI ≥0.115 API framework
uvicorn ≥0.32 ASGI server
aiosqlite ≥0.20 Async SQLite
httpx ≥0.27 Async HTTP (Navidrome proxy, weather)
Kokoro ≥0.8.4 ONNX TTS engine
PyTorch (CPU) latest CPU build Kokoro backend
soundfile ≥0.12 WAV encoding for TTS output
anthropic ≥0.40 Claude Haiku API client
espeak-ng system Kokoro phoneme backend
ffmpeg system Audio pipeline

Frontend

Component Version Purpose
React 18 UI framework
TypeScript 5 Type safety
Vite 5 Build tool
Tailwind CSS 3 Styling
Nginx (Alpine) latest Static file serving + API proxy

External Services

Service Required Purpose
Navidrome Yes Music library
Anthropic API No DJ break script generation
Open-Meteo No Current weather for breaks

API Endpoints

The backend exposes these endpoints under /api/:

Method Path Description
GET /api/setup/status Returns {configured: bool}
POST /api/setup/connect Verify and save Navidrome credentials (only while unconfigured)
GET /api/settings Get all settings (passwords masked as bool)
POST /api/settings Update settings (empty string = keep existing)
GET /api/genres List genres with at least one song
POST /api/genre Set active genre, queue a break
GET /api/next Get the next segment (song or break)
POST /api/vote Record love/like/dislike (love also stars in Navidrome)
POST /api/skip Record skip, invalidate pending break, trigger regeneration
GET /api/history Last 50 played tracks
GET /api/playlists List Navidrome playlists
POST /api/playlists Create a new playlist with a song
POST /api/playlists/{id}/add Add a song to an existing playlist
GET /api/audio/song/{id} Proxy Navidrome audio stream (Range-request aware)
GET /api/cover/{id} Proxy Navidrome cover art (keeps its signed URL server-side)
GET /api/audio/break/{filename} Serve a generated DJ break WAV
GET /api/health Health check with Navidrome ping
GET /api/catalog/status Catalog build progress and stats
POST /api/catalog/rebuild Force a full Phase 1 catalog rebuild
POST /api/catalog/infer Start Phase 2 AI genre inference
GET /api/genres/art Cover art URL for each genre (one random album per genre)
GET /api/audit/status Last audit results and running state
POST /api/audit/run Trigger a manual catalog audit and fix
GET /api/feeds List configured RSS/Atom feeds
POST /api/feeds Add a feed (validated on add)
PATCH /api/feeds/{id} Rename or enable/disable a feed
DELETE /api/feeds/{id} Remove a feed
GET /api/similar/diagnose Both similarity providers side by side: live? and how much of each is in this library (?artist=, ?limit= default 3, ?lb=0 to skip ListenBrainz, ?timeout= per-artist seconds)
GET /api/stats/overview Totals: plays, listening time, unique songs/artists/stations
GET /api/stats/top/songs Most-played songs, each with catalog_id and vote for inline actions (?limit=, ?genre=)
GET /api/stats/top/artists Most-played artists (?limit=, ?genre=)
GET /api/stats/top/skipped Most-skipped songs, with play counts, catalog_id and vote (?limit=)
GET /api/stats/stations Per-station plays, listening time, and top artist
GET /api/stats/activity Plays per day for the last N days, zero-filled (?days=)
GET /api/stats/hourly Plays per hour of day, all 24 buckets
GET /api/stats/song/{id} One song's plays, rank, skips, first/last played
GET /api/stations/saved List saved artist stations (favourites first)
POST /api/stations/saved Save an artist station
PATCH /api/stations/saved/{id} Rename or toggle favourite
DELETE /api/stations/saved/{id} Delete a saved station
POST /api/stations/saved/{id}/play Start a saved station

Catalog Audit

The backend runs a daily audit that compares every artist in Navidrome (by album count) against the local song_catalog. Artists where we have fewer songs than albums are refetched from Navidrome and any missing songs are inserted into the catalog.

The audit runs automatically once per day alongside the regular catalog rebuild. You can also trigger it manually:

curl -X POST http://your-server:8000/api/audit/run
curl http://your-server:8000/api/audit/status

The status response shows artists_checked, artists_flagged, songs_added, and the timestamp of the last run. Check the backend logs ([audit] lines) for per-artist detail.


Troubleshooting

Blank screen / 503 on startup

The app shows a setup page the first time (or if Navidrome credentials aren't saved). If you see an error instead, check that the backend container started:

docker compose logs backend

DJ breaks don't play

  1. Check the backend logs for Break generation error:
  2. Verify the Anthropic API key is saved in Settings
  3. Confirm the key has available credits at console.anthropic.com
  4. Without an API key, the app still works — breaks are simply skipped

No genres listed

The genre list comes from Navidrome. Make sure your library is scanned and songs have genre tags. In Navidrome, go to Settings → Library and trigger a scan if needed.

Build takes forever on ARM / low-power hardware

The RUN python -c "from kokoro import KPipeline; ..." Dockerfile step initializes PyTorch on CPU, which can take 10–45 minutes on slow hardware. Options:

  • Build on a faster machine (amd64 VPS) and push the image
  • Accept the slow build — subsequent builds are cached and instant
  • Run the build with --progress=plain to see it's still making progress

Songs keep repeating

Recency decay prevents replaying songs heard in the last 24 hours, but with a small library you may still hear repeats. The weighting won't avoid a song forever — it just reduces probability.

TTS audio sounds wrong / no audio on breaks

Check BREAKS_DIR is writable inside the container (the dj_data volume handles this automatically in the default compose setup). Inspect /api/audio/break/<filename> directly in the browser to confirm the WAV is being served.