diff --git a/.gitignore b/.gitignore
index 97c979c9..0781eb75 100644
--- a/.gitignore
+++ b/.gitignore
@@ -71,3 +71,6 @@ android/*.keystore
android/*.keystore.*
android/*.jks
android/keystore.properties
+
+# Python bytecode from the tools/ scripts
+__pycache__/
diff --git a/README.md b/README.md
index 83130240..2bad89b7 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,14 @@
Minstrel serves your music library to the web, to its own Android app, and to any Subsonic client. Shuffle, radio, likes and play history are worked out on the server, so every device gets the same mixes and the same history. It is for anyone who keeps their own music collection and wants it to sound like more than a random shuffle.
-
+
+
+
+
+
+
+
+The music in these screenshots is invented: every artist, album, cover and song was generated for them (tools/demo-library).
## Quick start
diff --git a/docs/screenshots/README.md b/docs/screenshots/README.md
index 21924960..dd603652 100644
--- a/docs/screenshots/README.md
+++ b/docs/screenshots/README.md
@@ -1,19 +1,21 @@
# README screenshots
-The root `README.md` shows `home.png`. The other files here are the set to
-capture for it. Export as PNG, capture while logged in as an admin and after
-the first library scan so nothing looks empty, and keep the same browser width
-and theme across all shots. Use a demo account and a library you are happy to
-publish: the shots go out with the repository.
+Every artist, album, cover and song in these screenshots is invented. They
+come from the demo library in [`tools/demo-library`](../../tools/demo-library),
+which also holds the steps and the script that retake them, so the set can be
+rebuilt whenever the UI changes. Retake them all at once, so they show the same
+library, account and listening history.
-| Filename | Route | What to capture |
+| File | Page | Shows |
|---|---|---|
-| `home.png` | `/` | The home page with a populated library (system playlists, recently added) |
-| `register.png` | `/register` | The account-creation form on a fresh instance |
-| `library-scan.png` | `/admin` | The library scan running in stages (grab it mid-scan so the stage tallies show) |
-| `collection.png` | `/collection` | The Collection queues: reports, duplicates, suspect sources and Needs a file |
-| `android-download.png` | `/settings` | The "Install the Android app" card |
-| `invite-users.png` | `/admin/users` | The users list and invite generation |
+| `home.png` | `/` | Home with two months of listening: the daily mixes, Songs like, and genre mixes |
+| `home-phone.png` | `/` | Home at phone width |
+| `now-playing.png` | `/now-playing` | A track playing, with its queue |
+| `album.png` | an album | A track list where one song has a featured guest |
+| `library.png` | `/library/albums` | The album grid |
+| `register.png` | `/register` | Creating the first account on a new server |
+| `android-download.png` | `/settings` | The Android app download card |
-To control the display width in the README, use an HTML tag instead of
-Markdown, e.g. `
`.
+The root `README.md` shows `home.png`, `now-playing.png` and `home-phone.png`.
+To set the display width there, use an HTML tag instead of Markdown, e.g.
+`
`.
diff --git a/docs/screenshots/album.png b/docs/screenshots/album.png
new file mode 100644
index 00000000..24ae4f45
Binary files /dev/null and b/docs/screenshots/album.png differ
diff --git a/docs/screenshots/android-download.png b/docs/screenshots/android-download.png
index 3775bb54..325d8d78 100644
Binary files a/docs/screenshots/android-download.png and b/docs/screenshots/android-download.png differ
diff --git a/docs/screenshots/home-phone.png b/docs/screenshots/home-phone.png
new file mode 100644
index 00000000..f4914367
Binary files /dev/null and b/docs/screenshots/home-phone.png differ
diff --git a/docs/screenshots/home.png b/docs/screenshots/home.png
index a0ed4f3d..057d36b0 100644
Binary files a/docs/screenshots/home.png and b/docs/screenshots/home.png differ
diff --git a/docs/screenshots/library.png b/docs/screenshots/library.png
new file mode 100644
index 00000000..fded9a1c
Binary files /dev/null and b/docs/screenshots/library.png differ
diff --git a/docs/screenshots/now-playing.png b/docs/screenshots/now-playing.png
new file mode 100644
index 00000000..d7c3f6ad
Binary files /dev/null and b/docs/screenshots/now-playing.png differ
diff --git a/docs/screenshots/register.png b/docs/screenshots/register.png
index 6346428d..1ef832a8 100644
Binary files a/docs/screenshots/register.png and b/docs/screenshots/register.png differ
diff --git a/tools/demo-library/README.md b/tools/demo-library/README.md
new file mode 100644
index 00000000..eb4d4bc2
--- /dev/null
+++ b/tools/demo-library/README.md
@@ -0,0 +1,66 @@
+# Demo library
+
+An invented music library for screenshots and demos. Every artist, album and
+song title is made up, every cover is drawn by `make_demo_library.py`, and
+every track is synthesised by ffmpeg, so nothing in it belongs to anyone.
+
+## Build the library
+
+Needs ffmpeg (with libmp3lame) and Pillow.
+
+```bash
+python3 tools/demo-library/make_demo_library.py /tmp/demo-music
+```
+
+About 24 albums and 208 tracks (about 350 MB). The script is seeded, so
+every run builds the same library. Pass `--covers-only` to redraw the covers
+and skip the audio.
+
+## Run a demo server
+
+`compose.yml` starts Minstrel and Postgres on a network with no internet
+access, as Minstrel is meant to run.
+
+```bash
+DEMO_MUSIC=/tmp/demo-music docker compose -f tools/demo-library/compose.yml up -d
+docker logs minstrel-demo-minstrel-1 2>&1 | grep setup_token
+```
+
+## Retake the README screenshots
+
+The captures run in the Playwright image on the demo network. That image
+carries the browsers but not the Python package, so install the matching
+package into a folder once (this step needs the internet):
+
+```bash
+mkdir -p /tmp/pwdeps /tmp/shots
+docker run --rm -v /tmp/pwdeps:/deps mcr.microsoft.com/playwright/python:v1.49.1-noble \
+ python3 -m pip install -q --break-system-packages --target /deps playwright==1.49.1
+CAPTURE="docker run --rm --network minstrel-demo_demo -v $PWD/tools/demo-library:/tools:ro \
+ -v /tmp/pwdeps:/deps:ro -v /tmp/shots:/shots -e PYTHONPATH=/deps --user $(id -u) -e HOME=/tmp \
+ mcr.microsoft.com/playwright/python:v1.49.1-noble python3 /tools/capture_screenshots.py"
+```
+
+Then:
+
+1. Once the first scan has finished, take the sign-up shot and create the
+ demo account:
+ `$CAPTURE register `
+2. Give the account two months of listening:
+
+ ```bash
+ docker exec minstrel-demo-postgres-1 psql -U minstrel -d minstrel -At -F, -c \
+ "SELECT t.id, t.genre, t.duration_ms, al.title FROM tracks t JOIN albums al ON al.id = t.album_id ORDER BY al.title, t.track_number" \
+ | python3 tools/demo-library/seed_history.py alex \
+ | docker exec -i minstrel-demo-postgres-1 psql -U minstrel -d minstrel -q -v ON_ERROR_STOP=1
+ ```
+
+3. Restart Minstrel so it builds the account's mixes:
+ `docker restart minstrel-demo-minstrel-1`, then wait half a minute.
+4. Capture the pages: `$CAPTURE pages`, then copy the PNGs you want from
+ `/tmp/shots` into `docs/screenshots/`.
+
+Leave out any page that shows the machine it ran on: the Admin overview
+lists the host's disk sizes.
+
+When you're done: `docker compose -f tools/demo-library/compose.yml down -v`.
diff --git a/tools/demo-library/capture_screenshots.py b/tools/demo-library/capture_screenshots.py
new file mode 100644
index 00000000..7214da3f
--- /dev/null
+++ b/tools/demo-library/capture_screenshots.py
@@ -0,0 +1,100 @@
+#!/usr/bin/env python3
+"""Capture the README screenshots from the demo stack.
+
+Runs inside the Playwright image on the demo stack's network (see README.md):
+creates the demo account on the fresh instance, or signs in to it, and saves
+each page as a PNG under /shots.
+
+ capture_screenshots.py register SETUP_TOKEN # fresh instance: sign-up shot + account
+ capture_screenshots.py pages # after seeding history and a restart
+"""
+
+from __future__ import annotations
+
+import sys
+
+from playwright.sync_api import Page, sync_playwright
+
+BASE = "http://minstrel:4533"
+USER, PASSWORD = "alex", "demo-password-123"
+STATE = "/shots/state.json"
+
+
+def settle(pg: Page, ms: int = 3000) -> None:
+ # Home holds a live event stream open, so the page never goes network-idle.
+ pg.wait_for_load_state("load")
+ pg.wait_for_timeout(ms)
+
+
+def register(token: str) -> None:
+ with sync_playwright() as p:
+ b = p.chromium.launch()
+ ctx = b.new_context(viewport={"width": 540, "height": 760}, device_scale_factor=2, color_scheme="dark")
+ pg = ctx.new_page()
+ pg.goto(f"{BASE}/register")
+ settle(pg, 1500)
+ pg.screenshot(path="/shots/register.png", full_page=True)
+ pg.fill("input[autocomplete=username]", USER)
+ pg.fill("input[autocomplete=name]", "Alex")
+ pw = pg.locator("input[autocomplete=new-password]")
+ pw.nth(0).fill(PASSWORD)
+ pw.nth(1).fill(PASSWORD)
+ pg.locator("input[autocomplete=off]").first.fill(token)
+ pg.click("button[type=submit]")
+ pg.wait_for_url(f"{BASE}/")
+ ctx.storage_state(path=STATE)
+ b.close()
+
+
+def pages() -> None:
+ with sync_playwright() as p:
+ b = p.chromium.launch(args=["--autoplay-policy=no-user-gesture-required"])
+ desk = b.new_context(viewport={"width": 1440, "height": 960}, device_scale_factor=1.25,
+ color_scheme="dark", storage_state=STATE)
+ pg = desk.new_page()
+ pg.on("pageerror", lambda e: print("page error:", e, file=sys.stderr))
+
+ pg.goto(f"{BASE}/")
+ settle(pg, 4000)
+ pg.screenshot(path="/shots/home.png")
+
+ pg.goto(f"{BASE}/library/albums")
+ settle(pg)
+ pg.screenshot(path="/shots/library.png")
+
+ pg.get_by_text("Harbour Lights Out").first.click()
+ settle(pg)
+ pg.screenshot(path="/shots/album.png")
+
+ pg.get_by_role("button", name="Play").first.click()
+ pg.wait_for_timeout(5000)
+ # Open Now playing from inside the app, as a link would: a full page
+ # load would start the player over, paused.
+ pg.evaluate("p => { const a = document.createElement('a'); a.href = p;"
+ " document.body.append(a); a.click(); a.remove(); }", "/now-playing")
+ pg.wait_for_timeout(3000)
+ pg.screenshot(path="/shots/now-playing.png")
+
+ pg.goto(f"{BASE}/settings")
+ settle(pg)
+ pg.get_by_text("Android app", exact=True).first.locator("xpath=ancestor::section[1]").screenshot(
+ path="/shots/android-download.png")
+ desk.close()
+
+ phone = b.new_context(viewport={"width": 390, "height": 844}, device_scale_factor=3,
+ color_scheme="dark", storage_state=STATE)
+ pg = phone.new_page()
+ pg.goto(f"{BASE}/")
+ settle(pg, 4000)
+ pg.screenshot(path="/shots/home-phone.png")
+ b.close()
+
+
+if __name__ == "__main__":
+ if len(sys.argv) >= 3 and sys.argv[1] == "register":
+ register(sys.argv[2])
+ elif len(sys.argv) == 2 and sys.argv[1] == "pages":
+ pages()
+ else:
+ print(__doc__, file=sys.stderr)
+ sys.exit(2)
diff --git a/tools/demo-library/compose.yml b/tools/demo-library/compose.yml
new file mode 100644
index 00000000..85fec30d
--- /dev/null
+++ b/tools/demo-library/compose.yml
@@ -0,0 +1,22 @@
+# A throwaway Minstrel on the demo library, for screenshots and demos.
+# The network is internal: nothing in this stack can reach the internet.
+#
+# DEMO_MUSIC=/path/to/demo-music docker compose -f tools/demo-library/compose.yml up -d
+name: minstrel-demo
+services:
+ minstrel:
+ image: git.fabledsword.com/bvandeusen/minstrel:dev
+ environment:
+ MINSTREL_DATABASE_URL: postgres://minstrel:minstrel@postgres:5432/minstrel?sslmode=disable
+ MINSTREL_LIBRARY_SCAN_PATHS: /music
+ volumes:
+ - ${DEMO_MUSIC:?set DEMO_MUSIC to the folder make_demo_library.py built}:/music:ro
+ depends_on: [postgres]
+ networks: [demo]
+ postgres:
+ image: postgres:17
+ environment: {POSTGRES_USER: minstrel, POSTGRES_PASSWORD: minstrel, POSTGRES_DB: minstrel}
+ networks: [demo]
+networks:
+ demo:
+ internal: true
diff --git a/tools/demo-library/make_demo_library.py b/tools/demo-library/make_demo_library.py
new file mode 100644
index 00000000..73981b11
--- /dev/null
+++ b/tools/demo-library/make_demo_library.py
@@ -0,0 +1,302 @@
+#!/usr/bin/env python3
+"""Build Minstrel's demo library: invented artists and albums, with generated
+cover art and generated audio, so screenshots and demos need no real music.
+
+Every artist, album and title here is made up, every cover is drawn by this
+script, and every track is synthesised by ffmpeg. Nothing is downloaded. The
+same seed always builds the same library.
+
+ python3 tools/demo-library/make_demo_library.py OUT_DIR
+
+Needs ffmpeg (with libmp3lame) and Pillow.
+"""
+
+from __future__ import annotations
+
+import argparse
+import math
+import random
+import shutil
+import subprocess
+import sys
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from PIL import Image, ImageDraw, ImageFilter, ImageFont
+
+SEED = 20261125
+COVER_PX = 800
+SAMPLE_RATE = 22050
+FONT_DIRS = [Path("/usr/share/fonts/truetype/dejavu"), Path("/usr/share/fonts/TTF")]
+
+
+@dataclass
+class Album:
+ artist: str
+ title: str
+ year: int
+ genre: str
+ tracks: int
+ style: str # how its cover is drawn
+ palette: tuple[str, ...]
+ # (track number, guest) for a track by "artist feat. guest".
+ features: dict[int, str] = field(default_factory=dict)
+
+
+CATALOGUE: list[Album] = [
+ Album("Low Tide Choir", "Saltwater Hymns", 2019, "Indie Rock", 10, "sun", ("#1d3557", "#e76f51", "#f4a261")),
+ Album("Low Tide Choir", "Harbour Lights Out", 2022, "Indie Rock", 9, "stripes", ("#0b132b", "#5bc0be", "#f2e9e4"),
+ features={4: "Ruby Calloway"}),
+ Album("Marrow & Moth", "Kindling", 2017, "Folk", 8, "rings", ("#3d2b1f", "#c08552", "#f3e9dc")),
+ Album("Marrow & Moth", "The Long Field", 2021, "Folk", 9, "hills", ("#283618", "#606c38", "#fefae0")),
+ Album("Copperline Static", "Neon Almanac", 2020, "Synthpop; Electronic", 10, "grid", ("#10002b", "#e0aaff", "#ff006e")),
+ Album("Copperline Static", "Afterglow Protocol", 2023, "Synthpop; Electronic", 8, "sun", ("#240046", "#ff5d8f", "#ffd166")),
+ Album("Juniper Vale Quartet", "Blue Hour Sketches", 2016, "Jazz", 7, "blocks", ("#023047", "#219ebc", "#ffb703")),
+ Album("Juniper Vale Quartet", "Late Set, Room Nine", 2020, "Jazz", 8, "type", ("#14213d", "#fca311", "#e5e5e5")),
+ Album("Hollow Atlas", "Cartography of Fog", 2018, "Ambient", 7, "blur", ("#2b2d42", "#8d99ae", "#edf2f4")),
+ Album("Hollow Atlas", "Slow Weather", 2024, "Ambient", 6, "waves", ("#003049", "#669bbc", "#fdf0d5")),
+ Album("Sundial Arcade", "Tape Hiss Afternoons", 2021, "Lo-Fi", 12, "blocks", ("#3a5a40", "#a3b18a", "#dad7cd")),
+ Album("Sundial Arcade", "Study Lamp", 2023, "Lo-Fi", 11, "rings", ("#432818", "#bb9457", "#ffe6a7")),
+ Album("The Paper Comets", "Bright Little Disasters", 2022, "Indie Rock", 10, "type", ("#ef476f", "#ffd166", "#073b4c")),
+ Album("Night Ferry Collective", "Undertow Radio", 2015, "Trip Hop; Electronic", 9, "waves", ("#161a1d", "#660708", "#e5383b")),
+ Album("Night Ferry Collective", "Glass District", 2019, "Trip Hop; Electronic", 8, "grid", ("#0d1b2a", "#415a77", "#e0e1dd")),
+ Album("Ruby Calloway", "Honey & Iron", 2018, "Soul", 10, "sun", ("#370617", "#dc2f02", "#ffba08")),
+ Album("Glacier Mouth", "We Were Here When the Lights Went", 2017, "Post-Rock; Ambient", 6, "hills", ("#03045e", "#0077b6", "#caf0f8")),
+ Album("Pixel Orchard", "Circuit Bloom", 2024, "Electronic", 9, "stripes", ("#001219", "#0a9396", "#e9d8a6")),
+ Album("Wren Halloway", "Small Rooms", 2023, "Folk", 8, "blur", ("#582f0e", "#a68a64", "#ede0d4")),
+ Album("Bramble & Bell", "Hedgerow Songs", 2020, "Folk", 9, "hills", ("#2d3a1f", "#8a9a5b", "#f1e3c6")),
+ Album("The Marlowe Trio", "Brushes at Midnight", 2019, "Jazz", 10, "rings", ("#1b1b3a", "#693668", "#f4c095")),
+ Album("Sable Cartwright", "Smoke Rings & Slow Tempos", 2021, "Jazz", 8, "blocks", ("#2b2118", "#a4243b", "#d8c99b")),
+ Album("Tidepool Engine", "Low Frequencies for Long Drives", 2022, "Ambient", 8, "waves", ("#0f2027", "#2c5364", "#a8dadc")),
+]
+
+# A compilation: one album, many performers, filed under Various Artists.
+COMPILATION = Album("Various Artists", "Sunday Morning Static", 2024, "Lo-Fi", 8, "type",
+ ("#264653", "#2a9d8f", "#e9c46a"))
+COMPILATION_ARTISTS = ["Sundial Arcade", "Hollow Atlas", "Wren Halloway", "Pixel Orchard",
+ "Juniper Vale Quartet", "Marrow & Moth", "Copperline Static", "Night Ferry Collective"]
+
+WORDS_A = ["Paper", "Silver", "Quiet", "Northbound", "Velvet", "Hollow", "Golden", "Static", "Borrowed",
+ "Midnight", "Lantern", "Coastal", "Glass", "Amber", "Second", "Soft", "Electric", "Wild",
+ "Slow", "Little", "Distant", "Winter", "Open", "Lucky", "Faded", "Common", "Copper", "Blue"]
+WORDS_B = ["Moons", "Harbour", "Signal", "Rooms", "Weather", "Orchard", "Engines", "Letters", "Tides",
+ "Gardens", "Satellites", "Mornings", "Rivers", "Postcards", "Streetlights", "Fields", "Hearts",
+ "Ferries", "Echoes", "Windows", "Islands", "Kites", "Stations", "Embers", "Comets", "Lines"]
+WORDS_C = ["Leaving", "Holding On", "Sleepwalk", "Undertow", "Homesick", "Daylight", "Wildfire", "Overpass",
+ "Driftwood", "Halfway", "Saltlines", "Afterhours", "Small Hours", "Overgrown", "Breathe Out",
+ "Low Light", "Signal Fire", "Weightless", "Runaway", "Fever Dream", "Goodnight", "Carousel"]
+
+NOTE_HZ = [261.63, 277.18, 293.66, 311.13, 329.63, 349.23, 369.99, 392.00, 415.30, 440.00, 466.16, 493.88]
+CHORDS = [(0, 4, 7), (0, 3, 7), (0, 4, 7, 11), (0, 3, 7, 10), (0, 5, 7), (0, 4, 9)]
+
+
+def track_titles(rng: random.Random, n: int) -> list[str]:
+ seen: set[str] = set()
+ out: list[str] = []
+ while len(out) < n:
+ shape = rng.random()
+ if shape < 0.35:
+ t = f"{rng.choice(WORDS_A)} {rng.choice(WORDS_B)}"
+ elif shape < 0.6:
+ t = rng.choice(WORDS_C)
+ elif shape < 0.8:
+ t = f"The {rng.choice(WORDS_A)} {rng.choice(WORDS_B)}"
+ else:
+ t = f"{rng.choice(WORDS_C)} ({rng.choice(WORDS_A)} {rng.choice(WORDS_B)})"
+ if t not in seen:
+ seen.add(t)
+ out.append(t)
+ return out
+
+
+def font(size: int, bold: bool = False) -> ImageFont.ImageFont:
+ name = "DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf"
+ for d in FONT_DIRS:
+ if (d / name).exists():
+ return ImageFont.truetype(str(d / name), size)
+ return ImageFont.load_default()
+
+
+def hex_rgb(h: str) -> tuple[int, int, int]:
+ return tuple(int(h[i:i + 2], 16) for i in (1, 3, 5)) # type: ignore[return-value]
+
+
+def mix(a: tuple[int, int, int], b: tuple[int, int, int], t: float) -> tuple[int, int, int]:
+ return tuple(round(x + (y - x) * t) for x, y in zip(a, b)) # type: ignore[return-value]
+
+
+def draw_cover(album: Album, rng: random.Random) -> Image.Image:
+ bg, mid, hi = (hex_rgb(c) for c in album.palette)
+ n = COVER_PX
+ img = Image.new("RGB", (n, n), bg)
+ d = ImageDraw.Draw(img)
+ for y in range(n): # vertical gradient as the base of every style
+ d.line([(0, y), (n, y)], fill=mix(bg, mid, (y / n) ** 1.6 * 0.55))
+
+ s = album.style
+ if s == "sun":
+ r = rng.randint(180, 260)
+ cx, cy = rng.randint(250, 550), rng.randint(250, 420)
+ for i in range(r, 0, -4):
+ d.ellipse([cx - i, cy - i, cx + i, cy + i], fill=mix(hi, mid, i / r * 0.5))
+ for k in range(6):
+ y = cy + 40 + k * 34
+ d.rectangle([0, y, n, y + 12 + k * 2], fill=bg)
+ elif s == "stripes":
+ w = rng.randint(28, 60)
+ for i, x in enumerate(range(-n, n * 2, w)):
+ d.polygon([(x, 0), (x + w // 2, 0), (x + w // 2 - n, n), (x - n, n)],
+ fill=(mid if i % 3 == 0 else hi if i % 3 == 1 else bg))
+ elif s == "rings":
+ cx, cy = n // 2 + rng.randint(-80, 80), n // 2 + rng.randint(-80, 80)
+ for i, r in enumerate(range(520, 20, -36)):
+ d.ellipse([cx - r, cy - r, cx + r, cy + r], outline=(hi if i % 2 else mid), width=14)
+ elif s == "hills":
+ for layer in range(5):
+ base = 330 + layer * 90
+ amp = rng.randint(30, 80)
+ ph = rng.random() * 6
+ period = rng.randint(90, 160)
+ pts = [(x, base + amp * math.sin(x / period + ph)) for x in range(0, n + 10, 10)]
+ d.polygon(pts + [(n, n), (0, n)], fill=mix(mid, hi, layer / 5) if layer < 3 else mix(bg, mid, layer / 6))
+ d.ellipse([560, 90, 680, 210], fill=hi)
+ elif s == "grid":
+ cell = rng.choice([80, 100])
+ for gx in range(0, n, cell):
+ for gy in range(0, n, cell):
+ if rng.random() < 0.45:
+ c = rng.choice([mid, hi, bg])
+ pad = rng.randint(6, 22)
+ d.rectangle([gx + pad, gy + pad, gx + cell - pad, gy + cell - pad], fill=c)
+ for gx in range(0, n, cell):
+ d.line([(gx, 0), (gx, n)], fill=mix(bg, hi, 0.25), width=2)
+ d.line([(0, gx), (n, gx)], fill=mix(bg, hi, 0.25), width=2)
+ elif s == "blocks":
+ for _ in range(9):
+ x0, y0 = rng.randint(-100, n - 100), rng.randint(-100, n - 100)
+ w, h = rng.randint(140, 420), rng.randint(140, 420)
+ d.rectangle([x0, y0, x0 + w, y0 + h], fill=rng.choice([mid, hi, mix(mid, hi, 0.5)]))
+ elif s == "waves":
+ for i in range(26):
+ y0 = 120 + i * 24
+ amp = 18 + i * 1.5
+ pts = [(x, y0 + amp * math.sin(x / 70 + i * 0.45)) for x in range(0, n + 8, 8)]
+ d.line(pts, fill=mix(mid, hi, i / 26), width=5)
+ elif s == "blur":
+ for _ in range(7):
+ r = rng.randint(120, 300)
+ cx, cy = rng.randint(0, n), rng.randint(0, n)
+ d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=rng.choice([mid, hi, mix(bg, hi, 0.6)]))
+ img = img.filter(ImageFilter.GaussianBlur(70))
+ d = ImageDraw.Draw(img)
+ elif s == "type":
+ word = album.title.split()[0].upper().strip(",")
+ f = font(220 if len(word) <= 5 else 150, bold=True)
+ for i in range(4):
+ d.text((40, 60 + i * 175), word, font=f, fill=(hi if i % 2 == 0 else mid))
+
+ # Every cover carries its artist and title, as a real sleeve would, over a
+ # dark fade so the light text reads on any artwork.
+ scrim = Image.new("L", (n, n), 0)
+ sd = ImageDraw.Draw(scrim)
+ for y in range(n - 260, n):
+ sd.line([(0, y), (n, y)], fill=round(170 * ((y - (n - 260)) / 260) ** 1.3))
+ img = Image.composite(Image.new("RGB", (n, n), (8, 8, 12)), img, scrim)
+ d = ImageDraw.Draw(img)
+ pad = 44
+ size = 44
+ while size > 22 and d.textlength(album.title, font=font(size, bold=True)) > n - 2 * pad:
+ size -= 2
+ d.text((pad, n - pad - 88), album.title, font=font(size, bold=True), fill=(250, 248, 242))
+ d.text((pad, n - pad - 36), album.artist, font=font(28), fill=(225, 222, 215))
+ return img
+
+
+def synth_expr(rng: random.Random) -> tuple[str, float]:
+ """An ffmpeg aevalsrc expression: a four-chord loop over a bass note,
+ pulsed at its own tempo. Each track draws its own roots, chord shapes and
+ tempo, so no two tracks fingerprint alike."""
+ bpm = rng.randint(68, 132)
+ beat = 60 / bpm
+ bar = beat * 4
+ roots = [rng.randrange(12) for _ in range(4)]
+ shapes = [rng.choice(CHORDS) for _ in range(4)]
+ loop = bar * 4
+ parts = []
+ for i, (root, shape) in enumerate(zip(roots, shapes)):
+ tones = "+".join(f"sin(2*PI*{NOTE_HZ[(root + iv) % 12] * (2 if iv >= 12 else 1):.2f}*t)" for iv in shape)
+ bass = f"0.9*sin(2*PI*{NOTE_HZ[root] / 4:.2f}*t)"
+ gate = f"between(mod(t,{loop:.4f}),{i * bar:.4f},{(i + 1) * bar - 0.001:.4f})"
+ parts.append(f"{gate}*(({tones})/{len(shape)}*0.5+{bass}*0.35)")
+ pulse = f"(0.65+0.35*exp(-6*mod(t,{beat:.4f})))"
+ return f"0.55*{pulse}*({'+'.join(parts)})", loop
+
+
+def render_track(job: dict) -> None:
+ out: Path = job["path"]
+ if out.exists():
+ return
+ meta = []
+ for k, v in job["tags"].items():
+ meta += ["-metadata", f"{k}={v}"]
+ dur = job["duration"]
+ cmd = [
+ "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
+ "-f", "lavfi", "-i", f"aevalsrc='{job['expr']}':s={SAMPLE_RATE}:d={dur}",
+ "-af", f"afade=t=in:d=2,afade=t=out:st={dur - 4}:d=4,volume=0.8",
+ "-ac", "1", "-c:a", "libmp3lame", "-b:a", "64k", "-id3v2_version", "3",
+ *meta, str(out),
+ ]
+ subprocess.run(cmd, check=True)
+
+
+def safe(name: str) -> str:
+ return "".join(c if c.isalnum() or c in " -_&'()," else "_" for c in name).strip()
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ ap.add_argument("out", type=Path, help="directory to build the library in")
+ ap.add_argument("--jobs", type=int, default=8, help="tracks rendered at once")
+ ap.add_argument("--covers-only", action="store_true", help="redraw the covers and skip the audio")
+ args = ap.parse_args()
+ if not shutil.which("ffmpeg"):
+ print("ffmpeg is needed", file=sys.stderr)
+ return 1
+
+ rng = random.Random(SEED)
+ jobs = []
+ for album in [*CATALOGUE, COMPILATION]:
+ folder = args.out / safe(album.artist) / f"{safe(album.title)} ({album.year})"
+ folder.mkdir(parents=True, exist_ok=True)
+ draw_cover(album, random.Random(f"{SEED}-{album.title}")).save(folder / "cover.jpg", quality=90)
+ titles = track_titles(rng, album.tracks)
+ for n, title in enumerate(titles, start=1):
+ if album is COMPILATION:
+ artist = COMPILATION_ARTISTS[(n - 1) % len(COMPILATION_ARTISTS)]
+ elif n in album.features:
+ artist = f"{album.artist} feat. {album.features[n]}"
+ else:
+ artist = album.artist
+ expr, loop = synth_expr(rng)
+ duration = max(loop * 3, rng.randint(140, 290))
+ tags = {
+ "title": title, "artist": artist, "album": album.title, "album_artist": album.artist,
+ "track": f"{n}/{album.tracks}", "disc": "1/1", "date": str(album.year), "genre": album.genre,
+ }
+ if album is COMPILATION:
+ tags["compilation"] = "1"
+ jobs.append({"path": folder / f"{n:02d} {safe(title)}.mp3", "expr": expr,
+ "duration": round(duration, 2), "tags": tags})
+
+ if args.covers_only:
+ return 0
+ with ThreadPoolExecutor(max_workers=args.jobs) as pool:
+ list(pool.map(render_track, jobs))
+ print(f"{len(jobs)} tracks in {len(CATALOGUE) + 1} albums under {args.out}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/demo-library/seed_history.py b/tools/demo-library/seed_history.py
new file mode 100644
index 00000000..53d654fa
--- /dev/null
+++ b/tools/demo-library/seed_history.py
@@ -0,0 +1,139 @@
+#!/usr/bin/env python3
+"""Give a demo account two months of believable listening, so Home has mixes,
+Rediscover, On this day and You might like to show.
+
+Reads the demo library's tracks as CSV on stdin and writes SQL on stdout:
+
+ psql -At -F, -c "SELECT t.id, t.genre, t.duration_ms, al.title
+ FROM tracks t JOIN albums al ON al.id = t.album_id" \\
+ | python3 tools/demo-library/seed_history.py alex | psql
+
+Run it on a demo instance after the first scan and before Minstrel next
+starts: Minstrel rebuilds each listener's mixes at startup.
+"""
+
+from __future__ import annotations
+
+import argparse
+import csv
+import random
+import sys
+import uuid
+from collections import Counter
+from datetime import datetime, timedelta, timezone
+
+SEED = 20261125
+DAYS = 60
+
+# How much the listener plays each genre: a few favourites, a long tail.
+GENRE_WEIGHT = {"Lo-Fi": 5, "Indie Rock": 5, "Synthpop": 4, "Trip Hop": 4, "Soul": 2, "Jazz": 2,
+ "Folk": 2, "Ambient": 1, "Post-Rock": 0.5, "Electronic": 0.3}
+# Never played, so they can be suggested as new.
+UNHEARD = {"Circuit Bloom", "Slow Weather", "Small Rooms"}
+# Played a lot a month or two ago and not since, for Rediscover.
+EARLIER_ONLY = {"Undertow Radio", "Kindling", "Glass District"}
+# Played around this date a year ago, for On this day.
+A_YEAR_AGO = {"Honey & Iron", "Blue Hour Sketches", "Saltwater Hymns"}
+
+
+def q(v: object) -> str:
+ return "NULL" if v is None else "'" + str(v).replace("'", "''") + "'"
+
+
+def ts(t: datetime) -> str:
+ return q(t.isoformat())
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ ap.add_argument("username")
+ args = ap.parse_args()
+ rng = random.Random(SEED)
+
+ # A track's first genre is the one its listener chose it for.
+ tracks = [{"id": r[0], "genre": r[1].split(";")[0].strip(), "ms": int(r[2] or 180000), "album": r[3]}
+ for r in csv.reader(sys.stdin) if r]
+ if not tracks:
+ print("no tracks on stdin", file=sys.stderr)
+ return 1
+ for t in tracks: # every album has a couple of tracks its listener loves
+ t["fav"] = rng.choice([1, 1, 1, 2, 4])
+
+ def pick(pool: list[dict]) -> dict:
+ return rng.choices(pool, weights=[GENRE_WEIGHT.get(t["genre"], 1) * t["fav"] for t in pool])[0]
+
+ recent = [t for t in tracks if t["album"] not in UNHEARD | EARLIER_ONLY]
+ earlier = [t for t in tracks if t["album"] not in UNHEARD]
+ year_ago = [t for t in tracks if t["album"] in A_YEAR_AGO]
+
+ user = f"(SELECT id FROM users WHERE username = {q(args.username)})"
+ now = datetime.now(timezone.utc).replace(microsecond=0)
+ out = ["BEGIN;"]
+ plays: Counter[str] = Counter()
+
+ def session(start: datetime, pool: list[dict], count: int, in_order: bool = False) -> None:
+ """One sitting: count shuffled picks from pool, or pool played straight through."""
+ sid = uuid.UUID(int=rng.getrandbits(128), version=4)
+ t = start
+ rows = []
+ for i in range(count):
+ tr = pool[i] if in_order else pick(pool)
+ skip_chance = 0.0 if in_order else 0.1 if GENRE_WEIGHT.get(tr["genre"], 1) >= 2 else 0.35
+ skipped = rng.random() < skip_chance
+ ratio = rng.uniform(0.05, 0.3) if skipped else rng.uniform(0.92, 1.0)
+ played = int(tr["ms"] * ratio)
+ end = t + timedelta(milliseconds=played)
+ rows.append(f"({user}, {q(tr['id'])}, {q(sid)}, {ts(t)}, {ts(end)}, {played}, {ratio:.3f}, "
+ f"{'true' if skipped else 'false'}, 'demo', 'direct')")
+ if not skipped:
+ plays[tr["id"]] += 1
+ t = end + timedelta(seconds=rng.randint(1, 4))
+ out.append(f"INSERT INTO play_sessions (id, user_id, started_at, ended_at, last_event_at, track_count, client_id) "
+ f"VALUES ({q(sid)}, {user}, {ts(start)}, {ts(t)}, {ts(t)}, {count}, 'demo');")
+ out.append("INSERT INTO play_events (user_id, track_id, session_id, started_at, ended_at, duration_played_ms, "
+ "completion_ratio, was_skipped, client_id, source) VALUES\n " + ",\n ".join(rows) + ";")
+
+ for day in range(DAYS, 0, -1):
+ if rng.random() < 0.15:
+ continue
+ date = (now - timedelta(days=day)).replace(hour=0, minute=0, second=0)
+ pool = earlier if day > 30 else recent
+ for _ in range(rng.choice([1, 1, 2])):
+ start = date + timedelta(hours=rng.choice([8, 12, 18, 20, 21]), minutes=rng.randint(0, 59))
+ session(start, pool, rng.randint(8, 16))
+ # Albums played through again and again a month or two back, then dropped:
+ # Rediscover offers tracks with three or more plays, none in 30 days.
+ for album in sorted(EARLIER_ONLY):
+ album_tracks = [t for t in tracks if t["album"] == album]
+ for k in range(4):
+ start = (now - timedelta(days=58 - k * 6)).replace(hour=19, minute=rng.randint(0, 59), second=0)
+ session(start, album_tracks, len(album_tracks), in_order=True)
+ session(now - timedelta(hours=3), recent, 12) # earlier today, for Last played
+ for d in range(-3, 4): # this week a year ago
+ session(now - timedelta(days=365 + d, hours=4), year_ago, rng.randint(5, 9))
+
+ loved = [tid for tid, _ in plays.most_common(18)]
+ out.append("INSERT INTO general_likes (user_id, track_id, liked_at) VALUES\n "
+ + ",\n ".join(f"({user}, {q(tid)}, {ts(now - timedelta(days=rng.randint(1, 50)))})" for tid in loved)
+ + "\nON CONFLICT DO NOTHING;")
+ out.append(f"""INSERT INTO general_likes_albums (user_id, album_id, liked_at)
+SELECT {user}, t.album_id, now() - interval '20 days' FROM play_events pe JOIN tracks t ON t.id = pe.track_id
+ WHERE pe.user_id = {user} AND NOT pe.was_skipped GROUP BY t.album_id ORDER BY count(*) DESC LIMIT 4
+ON CONFLICT DO NOTHING;""")
+ # Liked long ago and not played lately: what Rediscover brings back.
+ out.append(f"""INSERT INTO general_likes_albums (user_id, album_id, liked_at)
+SELECT {user}, al.id, now() - interval '45 days' FROM albums al
+ WHERE al.title IN ({", ".join(q(t) for t in sorted(EARLIER_ONLY))})
+ON CONFLICT DO NOTHING;""")
+ out.append(f"""INSERT INTO general_likes_artists (user_id, artist_id, liked_at)
+SELECT {user}, al.artist_id, now() - interval '25 days' FROM play_events pe JOIN tracks t ON t.id = pe.track_id
+ JOIN albums al ON al.id = t.album_id
+ WHERE pe.user_id = {user} AND NOT pe.was_skipped GROUP BY al.artist_id ORDER BY count(*) DESC LIMIT 3
+ON CONFLICT DO NOTHING;""")
+ out.append("COMMIT;")
+ print("\n".join(out))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())