Files
minstrel/tools/demo-library/seed_history.py
T
bvandeusenandClaude Opus 5.5 2bc6c60938
release / web (push) Successful in 1m16s
release / go (push) Successful in 1m47s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m1s
release / android (push) Successful in 4m31s
release / Build signed APK (push) Successful in 4m52s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 13s
release / Verify release artifacts (tag releases only) (push) Skipped
docs: README screenshots come from an invented demo library
Every artist, album, cover and song in the screenshots is generated by
tools/demo-library, so none of it is anyone's real music or art. The
folder builds the library (ffmpeg-synthesised audio, drawn covers),
gives a demo account two months of listening so every Home mix appears,
runs Minstrel and Postgres on a network with no internet, and retakes
the screenshots with Playwright. The README now shows Home, Now playing
and Home on a phone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:24:15 -05:00

140 lines
6.5 KiB
Python

#!/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())