Skip to content

About

A self-hosted Youtube Music stats tracker

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

ytm·tracker

A self-hosted YouTube Music tracker I built for myself, heavily inspired by stats.fm, one of the few things that kept me on Spotify as long as it did. Top artists and tracks, a listening streak, a plays-over-time chart, a weekday×hour heatmap, and a GitHub-style yearly calendar, over a few different date ranges.

Google doesn't expose a real listening-history API, so this pieces one together from two sources:

Source What it gives you Freshness
Google Takeout Complete history with exact timestamps Manual export, re-import anytime
Live polling (ytmusicapi) New plays from any device (iOS app, PC app, web) Every ~3 minutes

Live tracking works by taking the request headers off an active YouTube Music session in your browser and feeding them into the app, since there's no official API, this is really just borrowing your own login. Everything further back comes from a Google Takeout export.

A few known limitations: it doesn't catch a song replayed with nothing else played in between, playtime is an estimate rather than exact, and there's no per-album view, since album data turned out too inconsistent to bother building around.

Plays are recorded per profile, and brand accounts under your Google account work too, so you can track more than one "channel" side by side.

Screenshots

Dashboard overview Listening clock, streaks, and calendar Artist page

Setup

git clone https://github.com/gridoe/ytm-tracker.git
cd ytm-tracker

Then pick one of the two setups below, either way you'll end up at http://127.0.0.1:8000, where first boot just asks for your name (that becomes your first profile) and drops you onto Settings to hook up your listening history.

Docker (recommended)

docker compose up -d --build

Data (the SQLite DB and any saved browser-header auth files) persists in ./data on the host, so pulling updates and rebuilding (git pull && docker compose up -d --build) never touches it. restart: unless-stopped means it also comes back up on its own after a host reboot, no separate autostart setup needed.

Optional settings via a .env file next to docker-compose.yml:

  • YTM_PORT: host port to expose (default 8000)
  • YTM_POLL_INTERVAL: seconds between polls (default 180)
  • YTM_DISCORD_WEBHOOK: webhook URL for live-tracking failure/gap notifications. This just seeds the setting on first run; you can set or change it later from the app's Settings page without touching .env at all (see below).
Building your own multi-arch image (optional)

The image builds cleanly for both linux/amd64 and linux/arm64 with no extra flags. To build and publish one yourself:

docker buildx build --platform linux/amd64,linux/arm64 -t you/ytm-tracker --push .

Manual (Python + uv)

Requires Python 3.11+ (a uv venv with 3.12 works well):

uv venv --python 3.12 .venv
uv pip install -p .venv/bin/python -r requirements.txt
.venv/bin/uvicorn src.main:app --port 8000

Prerequisite: YouTube "Watch history" must not be paused (myactivity.google.com → Activity controls), or nothing gets recorded anywhere, Takeout included.

1. Backfill from Google Takeout

  1. Go to takeout.google.com → Deselect all → check YouTube and YouTube Music.
  2. Under "All YouTube data included" keep only history; under "Multiple formats" set history to JSON.
  3. Export, download, unzip, and find Takeout/YouTube and YouTube Music/history/watch-history.json. Folder and file names follow your account's language, e.g. a Greek account exports Takeout/YouTube και YouTube Music/ιστορικό/ιστορικό παρακολούθησης.json. The importer handles localized exports either way.
  4. Upload it on the Settings page (or CLI: .venv/bin/python -m src.importer path/to/watch-history.json --user 1, or with Docker: docker compose exec app python -m src.importer /app/data/watch-history.json --user 1 after copying the file into ./data first).

Re-importing a newer export later is safe: duplicates are skipped, and it also fixes up any plays live tracking had to guess the timestamp for (more on that below).

2. Connect live tracking

On Settings, paste your YouTube Music request headers once. This works no matter where the server runs (laptop, SBC, VPS), because the headers come from the browser on your computer, not the server's:

  1. Open music.youtube.com logged in.
  2. DevTools (F12) → Network tab → filter browse → click around in YT Music until a request shows up.
  3. Right-click the browse request → Copy → Copy request headers.
  4. Paste into the form, press Connect.

You never need to actually listen in the browser, since history is account-level, so plays from the iOS app or the PC app get picked up just the same. The session expires every few weeks; when the poller status on Settings shows an auth error, just repeat the copy-paste. (CLI alternative: .venv/bin/ytmusicapi browser --file data/browser.json.)

Run it automatically at login (macOS, manual setup only)

Docker users get this for free via restart: unless-stopped above, so skip this section. For the manual/.venv setup:

scripts/install-autostart.sh          # optional port argument, default 8000

Installs a LaunchAgent: starts at login, restarts if it crashes, logs to data/server.log. Remove with scripts/uninstall-autostart.sh. Remember the poller only records while the machine is actually awake; Takeout re-imports are what fill in any gaps from sleep/downtime.

3. Profiles / brand accounts (optional)

To track another profile under the same Google account, use Add a profile on the Settings page. There are two ways to connect it:

  • Simplest: if you're logged into the browser as that account/brand channel directly, just copy its headers the same way you did for the main profile (step 2 above). No extra ID needed, since the session already resolves to the right channel on its own.
  • Reusing one login for both: if you'd rather not log in and out, point the new profile at the same data/browser.json auth file as the main one and set its brand account ID, the long number from myaccount.google.com/brandaccounts (select the account; the ID is in the URL), which tells the app which linked channel to poll as under that shared session.

Either way, its Takeout is exported by switching to that profile at takeout.google.com first.

Once you've got more than one profile, the avatar menu in the top corner lets you switch between them from wherever you are: it stays on the same page, just showing that profile's data instead.

The Settings page

Everything that isn't a stat lives here, and it's the one page worth knowing your way around:

  • Import Google Takeout history and Live tracking: the two setup steps above; come back here any time to re-import a newer Takeout export or reconnect an expired session.
  • Discord notifications: paste a Discord webhook URL and you'll get pinged if live tracking breaks (expired session, server error) instead of silently missing plays until you happen to check. This is the same setting as YTM_DISCORD_WEBHOOK, just editable without redeploying.
  • Dashboard widgets: show/hide the listening clock, listening calendar, streaks, and "most active" sections on the dashboard, per taste.
  • Manage profiles: rename a profile, set/change its brand-account ID, disconnect live tracking, or delete its data. Two different delete buttons here are worth reading twice before clicking: delete imported plays only removes Takeout-sourced plays (re-importing brings them back), while delete all plays also wipes anything live tracking picked up, which can't be recovered since there's no Takeout record of it. Delete profile removes the profile itself, along with its plays and saved login.
  • Add a profile: set up tracking for another account or brand channel.

How live tracking works (and its accuracy)

The YT Music history endpoint doesn't come with timestamps and collapses repeat plays, so the poller compares consecutive snapshots: anything that shows up above the previously-seen top of the list is a new play, stamped at poll time (and backdated by track duration if a few landed in one gap). At the default 3-minute interval, timestamps land within a few minutes of reality. Replayed tracks get caught too, since a repeat jumps back to the top of the list.

A few limitations, accepted by design rather than considered bugs:

  • If more plays happen than fit in one polling gap's visible history (say, the app is down for a week), the plays that get pushed off the list are missed. The next Takeout import fills them back in.
  • A track replayed within 60 seconds of its previous recorded play is treated as the same play, a safety net against overlapping poll runs, not against genuine fast repeats. A Takeout re-import always replaces poll-tracked plays with the real timestamps regardless of timing, so genuine rapid repeats end up counted correctly once you next re-import.
  • Replaying a track with nothing else played in between won't be seen by live tracking at all until something else plays first. YT Music's own history list collapses immediate repeats rather than logging each one, and the poller can only notice a new play when the list's head actually changes. A Takeout re-import always has the real count.
  • ytmusicapi is unofficial, so a YT frontend change can break polling until the library catches up. The poller fails soft and surfaces the error on Settings rather than crashing anything.

Album data is a partial picture for the same reason: it's only ever seen for plays that live tracking catches (Takeout exports don't include it), so there's no dedicated albums page yet, just a track's album name where it's known, plus a /api/top/albums endpoint for anyone who wants to poke at what's there.

Configuration

Copy .env.example to .env (or export the variables):

  • YTM_POLL_INTERVAL: seconds between polls (default 180)
  • YTM_DATA_DIR: where the SQLite DB and auth files live (default ./data)

API

The UI is backed by JSON endpoints usable directly. All take ?user= and ?range=4w|6m|all|today|week|year (year is the current calendar year, Jan 1 to now), or range=custom with start=YYYY-MM-DD&end=YYYY-MM-DD:

/api/overview, /api/top/tracks, /api/top/artists, /api/top/albums, /api/plays-per-day, /api/heatmap, /api/recent

About

A self-hosted Youtube Music stats tracker

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages