nixamp 0.55.1 → 0.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/ai-label.d.ts +38 -3
  2. package/dist/ai-label.js +96 -5
  3. package/dist/label-profiles.d.ts +60 -0
  4. package/dist/label-profiles.js +190 -0
  5. package/dist/label-routes.js +29 -2
  6. package/dist/radio-pages.d.ts +14 -1
  7. package/dist/radio-pages.js +30 -3
  8. package/dist/server.js +12 -3
  9. package/package.json +1 -1
  10. package/src/ai-label.ts +95 -8
  11. package/src/label-profiles.ts +212 -0
  12. package/src/label-routes.ts +30 -2
  13. package/src/radio-pages.ts +28 -3
  14. package/src/server.ts +11 -3
  15. package/web/dist/assets/{ar-Huo4sgiY.js → ar-CwZJb_gN.js} +1 -1
  16. package/web/dist/assets/{cs-BBOuUwXU.js → cs-BQeUHU5U.js} +1 -1
  17. package/web/dist/assets/{da-Cev5Z6T9.js → da-B9gLGX-j.js} +1 -1
  18. package/web/dist/assets/{de-bQVDBh55.js → de-BtKJqMyc.js} +1 -1
  19. package/web/dist/assets/{es-CJuqtDkS.js → es-xCZPNIQ8.js} +1 -1
  20. package/web/dist/assets/{fi-7nU502Tj.js → fi-Bs6hJxj9.js} +1 -1
  21. package/web/dist/assets/{fr-BcVNUetg.js → fr-Db3viYEV.js} +1 -1
  22. package/web/dist/assets/{hi-9TAve2EY.js → hi-BEO0uXMK.js} +1 -1
  23. package/web/dist/assets/{hu-BTlBWSxB.js → hu-DddOFPOR.js} +1 -1
  24. package/web/dist/assets/{id-BX3ed0n3.js → id-Ca4dDDtC.js} +1 -1
  25. package/web/dist/assets/{it-BJUV5qZb.js → it-B9cFkgz7.js} +1 -1
  26. package/web/dist/assets/{main-BWhCWFcj.js → main-CHubaPAu.js} +2 -2
  27. package/web/dist/assets/{nl-H4pjCJkd.js → nl-kUxjpAwG.js} +1 -1
  28. package/web/dist/assets/{ru-GzkqrNgF.js → ru-BE9Sxy3t.js} +1 -1
  29. package/web/dist/assets/{station-DGgba3hs.js → station-DxBlD6Yl.js} +1 -1
  30. package/web/dist/assets/{sv-B5CF3sTx.js → sv-Cp6BIRXI.js} +1 -1
  31. package/web/dist/assets/{uk-M0JP5Z7P.js → uk-DavLH9cs.js} +1 -1
  32. package/web/dist/assets/{vi-D4kPYAxo.js → vi-eAlsSX6P.js} +1 -1
  33. package/web/dist/assets/{zh-DsrXJGeN.js → zh-D2Y8KIQG.js} +1 -1
  34. package/web/dist/index.html +1 -1
  35. package/web/dist/station.html +1 -1
  36. package/web/dist/sw.js +20 -20
@@ -26,9 +26,33 @@ export const RADIO_STATION = /^\/radio\/([a-z0-9-]{1,60})\/?$/;
26
26
  export const RADIO_ARTIST = /^\/radio\/artist\/([a-z0-9-]{1,90})\/?$/;
27
27
  export const RADIO_ALBUM = /^\/radio\/album\/([a-z0-9-]{1,100})(\/cover\.jpg)?\/?$/;
28
28
  export function isRadioPath(path) {
29
- return path === "/radio" || path === "/radio/" || RADIO_SUB.test(path) || RADIO_STATION.test(path) || RADIO_ARTIST.test(path) || RADIO_ALBUM.test(path);
29
+ return path === "/radio" || path === "/radio/" || path === RADIO_BUY || RADIO_SUB.test(path) || RADIO_STATION.test(path) || RADIO_ARTIST.test(path) || RADIO_ALBUM.test(path);
30
+ }
31
+ const RESERVED = new Set(["artist", "album", "artists", "albums", "buy"]);
32
+ /**
33
+ * Buy, through this server: a 302 to nixamp.com's store page for it, so the
34
+ * link on a /radio page does not carry the machine the music is on.
35
+ */
36
+ export const RADIO_BUY = "/radio/buy";
37
+ /** /radio/buy?kind=&artist=&album=&n=, checked: the label's keys and nothing else. */
38
+ export function radioBuyQuery(query) {
39
+ const kind = query.get("kind");
40
+ const artist = query.get("artist") ?? "";
41
+ const album = query.get("album") ?? "";
42
+ const n = Number(query.get("n") ?? 0);
43
+ if (kind !== "song" && kind !== "album" && kind !== "artist")
44
+ return null;
45
+ if (!/^[a-f0-9]{10}$/.test(artist))
46
+ return null;
47
+ if (kind !== "artist" && !/^[a-f0-9]{8}$/.test(album))
48
+ return null;
49
+ if (kind === "song" && !(Number.isInteger(n) && n >= 1 && n <= 999))
50
+ return null;
51
+ return { kind, artist, album: kind === "artist" ? "" : album, n: kind === "song" ? n : 0 };
52
+ }
53
+ export function radioBuyLink(kind, artist, album = "", n = 0) {
54
+ return `${RADIO_BUY}?${new URLSearchParams({ kind, artist, ...(kind !== "artist" ? { album } : {}), ...(kind === "song" ? { n: String(n) } : {}) }).toString()}`;
30
55
  }
31
- const RESERVED = new Set(["artist", "album", "artists", "albums"]);
32
56
  /**
33
57
  * Public, listed stations by name. Oldest first, so a name stays with the
34
58
  * station that had it; a second "Jazz" is jazz-2.
@@ -180,11 +204,14 @@ export function rewriteResponse(response, rewrite) {
180
204
  response.end = (chunk, ...rest) => end(swap(chunk), ...rest);
181
205
  }
182
206
  /** The station's addresses and token, as /radio/<name> says them instead. */
183
- export function radioRewriter(station, slug) {
207
+ export function radioRewriter(station, slug, buyFrom = "") {
184
208
  const token = station.listenToken;
185
209
  const encoded = encodeURIComponent(token);
186
210
  return (text) => {
187
211
  let out = text.split(`/api/v1/stations/${station.id}/`).join(`/radio/${slug}/`);
212
+ // The store's links name this server; /radio/buy sends there without saying so.
213
+ if (buyFrom)
214
+ out = out.split(buyFrom).join(`${RADIO_BUY}?`);
188
215
  for (const one of new Set([encoded, token])) {
189
216
  out = out.split(`?t=${one}&`).join("?").split(`&t=${one}`).join("").split(`?t=${one}`).join("").split(one).join("");
190
217
  }
package/dist/server.js CHANGED
@@ -77,7 +77,7 @@ import { handleRooms, RoomProbe, roomEntries, RoomStore, watchBase } from "./gui
77
77
  import { handleVods, VodProbe, vodEntries, VodStore, vodView } from "./guide-vods.js";
78
78
  import { withPitFooter } from "./pit-footer.js";
79
79
  import { handleFollowPage } from "./follow-page.js";
80
- import { asRadioPage, buildCatalogue, isRadioPath, NAV_STYLE, RADIO_ALBUM, RADIO_ARTIST, RADIO_CSP, RADIO_STATION, RADIO_SUB, radioNav, radioPeers, radioRewriter, radioStations, renderAlbum, renderArtist, renderDirectory, renderMissing, rewriteResponse, } from "./radio-pages.js";
80
+ import { asRadioPage, buildCatalogue, isRadioPath, NAV_STYLE, RADIO_ALBUM, RADIO_ARTIST, RADIO_CSP, RADIO_STATION, RADIO_SUB, RADIO_BUY, radioBuyLink, radioBuyQuery, radioNav, radioPeers, radioRewriter, radioStations, renderAlbum, renderArtist, renderDirectory, renderMissing, rewriteResponse, } from "./radio-pages.js";
81
81
  import { adCsp, guideAds, guideCsp, withPageAd, guideHosts, guidePeers, peerBase, PeerGuides, renderGuide } from "./station-guide.js";
82
82
  import { StationRunner } from "./station-runner.js";
83
83
  import { StationError, StationStore, channelOf, stationOfChannel } from "./stations.js";
@@ -1590,7 +1590,8 @@ export function createHandler(engine, options) {
1590
1590
  query.delete("t");
1591
1591
  query.set("t", station.listenToken);
1592
1592
  request.url = `/api/v1/stations/${station.id}/${sub[2]}?${query.toString()}`;
1593
- rewriteResponse(response, radioRewriter(station, sub[1]));
1593
+ const here = options.stations.publicBase?.() ?? "";
1594
+ rewriteResponse(response, radioRewriter(station, sub[1], /^https:\/\//.test(here) ? `${storeSite}/buy?server=${encodeURIComponent(here)}&` : ""));
1594
1595
  return handle(request, response);
1595
1596
  }
1596
1597
  }
@@ -2610,10 +2611,18 @@ export function createHandler(engine, options) {
2610
2611
  response.end(request.method === "HEAD" ? undefined : page);
2611
2612
  };
2612
2613
  const shop = stations.label && /^https:\/\//.test(publicBase)
2613
- ? { site: storeSite, buy: (kind, artist, album = "", n = 0) => buyLink(storeSite, publicBase, kind, artist, album, n), prices: PRICES }
2614
+ ? { site: storeSite, buy: radioBuyLink, prices: PRICES }
2614
2615
  : null;
2615
2616
  const peers = stations.peers ? radioPeers(named.keys(), await stations.peers.entries()) : new Map();
2616
2617
  const stationNames = new Map([...named].map(([slug, one]) => [slug, one.name]));
2618
+ if (path === RADIO_BUY) {
2619
+ const item = radioBuyQuery(url.searchParams);
2620
+ if (!item || !shop)
2621
+ return send(404, renderMissing("thing for sale", base, nav));
2622
+ response.writeHead(302, { location: buyLink(storeSite, publicBase, item.kind, item.artist, item.album, item.n), "cache-control": "no-store", "referrer-policy": "no-referrer" });
2623
+ response.end();
2624
+ return;
2625
+ }
2617
2626
  if (path === "/radio" || path === "/radio/") {
2618
2627
  const encrypted = request.socket.encrypted === true;
2619
2628
  const entries = guideEntries({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nixamp",
3
- "version": "0.55.1",
3
+ "version": "0.56.0",
4
4
  "description": "It really whips the terminal's ass. A Winamp-shaped audio player for your terminal.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/ai-label.ts CHANGED
@@ -34,6 +34,7 @@ import { aiKey } from "./ai-keys.ts";
34
34
  import { composerFromEnv, OutOfCredit, type Composer } from "./ai-radio.ts";
35
35
  import { askJson, hasModel } from "./ai-text.ts";
36
36
  import { formatLrc, type SyncedLine } from "./lyrics.ts";
37
+ import { bandMarkdown, castLine, inventMembers, readMembers, writeMembers, type Member } from "./label-profiles.ts";
37
38
  import type { LibraryIndex, Probed } from "./library-index.ts";
38
39
  import type { StationRunner } from "./station-runner.ts";
39
40
  import { StationError, type StationStore } from "./stations.ts";
@@ -94,6 +95,8 @@ export interface LabelArtist {
94
95
  themes: string;
95
96
  enabled: boolean;
96
97
  albums: LabelAlbum[];
98
+ /** Its people, by slug: each has members/<slug>.md and .jpg in the artist's folder (label-profiles.ts). */
99
+ members?: string[];
97
100
  createdAt: number;
98
101
  lastAttemptAt: number;
99
102
  lastError: string;
@@ -426,7 +429,7 @@ const LYRICS_SYSTEM = [
426
429
  ].join(" ");
427
430
 
428
431
  export async function planAlbum(
429
- artist: Pick<LabelArtist, "name" | "genre" | "sound" | "voice" | "bio" | "themes" | "albums">,
432
+ artist: Pick<LabelArtist, "name" | "genre" | "sound" | "voice" | "bio" | "themes" | "albums"> & { cast?: string },
430
433
  songs: number,
431
434
  ask: typeof askJson = askJson,
432
435
  ): Promise<{ title: string; concept: string; songs: Array<{ title: string; style: string }>; model: string }> {
@@ -440,6 +443,7 @@ export async function planAlbum(
440
443
  `Voice: ${artist.voice}`,
441
444
  artist.bio ? `Who they are: ${artist.bio}` : "",
442
445
  artist.themes ? `What they sing about: ${artist.themes}` : "",
446
+ artist.cast ? `The band, as they are (write for these people): ${artist.cast}` : "",
443
447
  before.length ? `Albums already out (do not reuse their titles or song titles; take the story somewhere new): ${before.join(" | ")}` : "This is the artist's debut album.",
444
448
  `The album has exactly ${songs} songs.`,
445
449
  ].filter(Boolean).join("\n"),
@@ -481,7 +485,7 @@ export async function inventArtist(genre: string, taken: string[], ask: typeof a
481
485
  }
482
486
 
483
487
  export async function writeLyrics(
484
- artist: Pick<LabelArtist, "name" | "genre" | "voice" | "themes">,
488
+ artist: Pick<LabelArtist, "name" | "genre" | "voice" | "themes"> & { cast?: string },
485
489
  album: Pick<LabelAlbum, "title" | "concept">,
486
490
  song: Pick<LabelSong, "title" | "style" | "seconds">,
487
491
  ask: typeof askJson = askJson,
@@ -491,6 +495,7 @@ export async function writeLyrics(
491
495
  prompt: [
492
496
  `Artist: ${artist.name} (${artist.genre}); voice: ${artist.voice}`,
493
497
  artist.themes ? `What they sing about: ${artist.themes}` : "",
498
+ artist.cast ? `Who sings and plays it (their voice and personality shape the words): ${artist.cast}` : "",
494
499
  `Album: "${album.title}"${album.concept ? `: ${album.concept}` : ""}`,
495
500
  `Song: "${song.title}": ${song.style}`,
496
501
  `The song lasts about ${song.seconds} seconds: keep the words under ${Math.max(600, Math.round(song.seconds * 10))} characters.`,
@@ -583,7 +588,7 @@ const STORYBOARD_SYSTEM = [
583
588
 
584
589
  /** Image prompts for a song's video, one a scene, from its words and mood. */
585
590
  export async function writeStoryboard(
586
- artist: Pick<LabelArtist, "name" | "genre" | "sound">,
591
+ artist: Pick<LabelArtist, "name" | "genre" | "sound"> & { cast?: string },
587
592
  album: Pick<LabelAlbum, "title" | "concept">,
588
593
  song: Pick<LabelSong, "title" | "style" | "lyrics">,
589
594
  scenes: number,
@@ -593,6 +598,7 @@ export async function writeStoryboard(
593
598
  system: STORYBOARD_SYSTEM,
594
599
  prompt: [
595
600
  `Song: "${song.title}" by ${artist.name} (${artist.genre}; ${artist.sound}), from "${album.title}"${album.concept ? `: ${album.concept}` : ""}`,
601
+ artist.cast ? `The band (these are the only performers; whenever one appears, name them and repeat their full look in that prompt, the image model remembers nothing): ${artist.cast}` : "",
596
602
  `Mood and arrangement: ${song.style}`,
597
603
  song.lyrics ? `Lyrics:\n${song.lyrics.slice(0, 1800)}` : "",
598
604
  `Exactly ${scenes} scenes.`,
@@ -746,6 +752,7 @@ export class AiLabel {
746
752
  private settings: LabelSettings = { ...DEFAULTS, pausedReason: "" };
747
753
  private usage: Record<string, number> = {};
748
754
  private running = false;
755
+ private profiling = false;
749
756
  /** Songs being made now, by `<album>:<n>`. */
750
757
  private claims = new Map<string, { label: string; seconds: number }>();
751
758
  /** Artists whose next album is being planned now. */
@@ -976,7 +983,8 @@ export class AiLabel {
976
983
  if (!this.canAsk()) throw new StationError("no_writer", "no language model to write the album: set GEMINI_API_KEY, OPENAI_API_KEY (or NIXAMP_OPENAI_URL) or ANTHROPIC_API_KEY", 409);
977
984
  const pending = artist.albums.find((one) => !one.doneAt);
978
985
  if (pending) throw new StationError("album_in_progress", `"${pending.title}" is still being made`, 409);
979
- const plan = await planAlbum(artist, this.settings.songsPerAlbum, this.deps.ask ?? askJson);
986
+ await this.ensureProfile(artist).catch(() => undefined);
987
+ const plan = await planAlbum({ ...artist, cast: this.castOf(artist) }, this.settings.songsPerAlbum, this.deps.ask ?? askJson);
980
988
  const year = new Date(this.now()).getUTCFullYear();
981
989
  let title = plan.title;
982
990
  if (artist.albums.some((one) => one.title.toLowerCase() === title.toLowerCase())) title = `${title} II`;
@@ -1005,7 +1013,8 @@ export class AiLabel {
1005
1013
  this.timer = setInterval(() => { void this.tick(); void this.videos(); }, everyMs);
1006
1014
  this.timer.unref?.();
1007
1015
  void this.tick();
1008
- void this.videos();
1016
+ // Profiles first (quick), so videos made after cast the right people.
1017
+ void this.profiles().finally(() => void this.videos());
1009
1018
  }
1010
1019
 
1011
1020
  /**
@@ -1132,7 +1141,7 @@ export class AiLabel {
1132
1141
  if (this.canAsk()) {
1133
1142
  try {
1134
1143
  const count = Math.max(4, Math.min(16, Math.round(seconds / 9)));
1135
- const prompts = await writeStoryboard(artist, album, song, count, this.deps.ask ?? askJson);
1144
+ const prompts = await writeStoryboard({ ...artist, cast: this.castOf(artist) }, album, song, count, this.deps.ask ?? askJson);
1136
1145
  mkdirSync(scenes, { recursive: true });
1137
1146
  const draw = this.deps.image ?? ((prompt: string) => workersAiCover(prompt));
1138
1147
  // A few at a time: the image model is quick, the machine is shared.
@@ -1334,7 +1343,7 @@ export class AiLabel {
1334
1343
  try {
1335
1344
  let writer = song.made || album.writer;
1336
1345
  if (!song.lyrics) {
1337
- const written = await writeLyrics(artist, album, song, this.deps.ask ?? askJson);
1346
+ const written = await writeLyrics({ ...artist, cast: this.castOf(artist) }, album, song, this.deps.ask ?? askJson);
1338
1347
  song.lyrics = written.lyrics;
1339
1348
  writer = written.model;
1340
1349
  song.made = writer;
@@ -1374,6 +1383,7 @@ export class AiLabel {
1374
1383
  if (album.songs.every((one) => one.file)) {
1375
1384
  album.doneAt = this.now();
1376
1385
  this.log(`${artist.name} released "${album.title}"`);
1386
+ void this.ensureProfile(artist).catch(() => undefined);
1377
1387
  }
1378
1388
  this.save();
1379
1389
  this.writeAlbumJson(artist, album);
@@ -1399,7 +1409,8 @@ export class AiLabel {
1399
1409
  }
1400
1410
 
1401
1411
  private async drawCover(artist: LabelArtist, album: LabelAlbum): Promise<void> {
1402
- const prompt = `Album cover art for "${album.title}", a ${artist.genre} album by ${artist.name}. ${album.concept} Style: ${artist.sound}. Striking, original, square composition. No text, no letters, no logos, no watermark.`;
1412
+ const cast = this.castOf(artist);
1413
+ const prompt = `Album cover art for "${album.title}", a ${artist.genre} album by ${artist.name}. ${album.concept} Style: ${artist.sound}.${cast ? ` If the band appears, they look exactly like this: ${cast}.` : ""} Striking, original, square composition. No text, no letters, no logos, no watermark.`;
1403
1414
  try {
1404
1415
  const picture = await (this.deps.cover ?? ((text) => workersAiCover(text)))(prompt);
1405
1416
  if (picture) {
@@ -1485,6 +1496,7 @@ export class AiLabel {
1485
1496
  .filter((one) => one.genre === genre)
1486
1497
  .map((one) => ({
1487
1498
  key: one.key, name: one.name, genre: one.genre, bio: one.bio,
1499
+ members: this.cast(one).map((member) => ({ slug: member.slug, name: member.name, role: member.role, bio: member.bio })),
1488
1500
  albums: one.albums
1489
1501
  .filter((album) => album.songs.some((song) => song.file))
1490
1502
  .map((album) => ({
@@ -1520,6 +1532,67 @@ export class AiLabel {
1520
1532
  return null;
1521
1533
  }
1522
1534
 
1535
+ /** The artist's folder: <root>/<genre>/<artist>/, where its albums and profile pages live. */
1536
+ folderOf(artist: Pick<LabelArtist, "genre" | "name">): string {
1537
+ return join(this.root, genreSlug(artist.genre), fileName(artist.name));
1538
+ }
1539
+
1540
+ /** The artist's people as their pages say now (hand edits win). */
1541
+ cast(artist: LabelArtist): Member[] {
1542
+ return readMembers(this.folderOf(artist), artist.members ?? []);
1543
+ }
1544
+
1545
+ /** The people in one line, for a prompt; "" before they are cast. */
1546
+ castOf(artist: LabelArtist): string {
1547
+ return castLine(this.cast(artist));
1548
+ }
1549
+
1550
+ /**
1551
+ * The artist's profile: its members invented once (and their portraits
1552
+ * drawn), and artist.md written again with what it has released.
1553
+ */
1554
+ async ensureProfile(artist: LabelArtist): Promise<void> {
1555
+ const folder = this.folderOf(artist);
1556
+ mkdirSync(folder, { recursive: true });
1557
+ const band = { name: artist.name, genre: artist.genre, holder: this.settings.holder };
1558
+ const draw = this.deps.image === undefined ? (prompt: string) => workersAiCover(prompt) : this.deps.image;
1559
+ if (!artist.members?.length && this.canAsk()) {
1560
+ const invented = await inventMembers(artist, this.deps.ask ?? askJson);
1561
+ const written = await writeMembers(folder, invented, band, draw);
1562
+ artist.members = written.map((one) => one.slug);
1563
+ this.save();
1564
+ this.log(`${artist.name}: ${written.map((one) => `${one.name} (${one.role})`).join(", ")}`);
1565
+ } else if (artist.members?.length) {
1566
+ // Portraits that are missing (a page added by hand, a failed drawing) are drawn now.
1567
+ await writeMembers(folder, this.cast(artist), band, draw);
1568
+ }
1569
+ writeFileSync(join(folder, "artist.md"), bandMarkdown({
1570
+ ...artist, holder: this.settings.holder, members: this.cast(artist),
1571
+ albums: artist.albums.filter((one) => one.doneAt || one.songs.some((song) => song.file)).map((one) => ({ year: one.year, title: one.title })),
1572
+ }));
1573
+ }
1574
+
1575
+ /** Every artist's profile, made or brought up to date; one at a time. */
1576
+ async profiles(): Promise<void> {
1577
+ if (this.profiling) return;
1578
+ this.profiling = true;
1579
+ try {
1580
+ for (const artist of this.list()) await this.ensureProfile(artist).catch((error: unknown) => this.log(`no profile for ${artist.name}: ${(error as Error).message}`));
1581
+ } finally {
1582
+ this.profiling = false;
1583
+ }
1584
+ }
1585
+
1586
+ /** A profile file anybody may read: artist.md, members/<slug>.md or members/<slug>.jpg. */
1587
+ profileFile(artistKey: string, what: string): { path: string; type: string } | null {
1588
+ const artist = this.artists.get(artistKey);
1589
+ if (!artist) return null;
1590
+ if (what === "artist.md") return { path: join(this.folderOf(artist), "artist.md"), type: "text/markdown; charset=utf-8" };
1591
+ const match = /^members\/([a-z0-9-]{1,40})\.(md|jpg)$/.exec(what);
1592
+ if (!match || !(artist.members ?? []).includes(match[1]!)) return null;
1593
+ return { path: join(this.folderOf(artist), "members", `${match[1]}.${match[2]}`), type: match[2] === "md" ? "text/markdown; charset=utf-8" : "image/jpeg" };
1594
+ }
1595
+
1523
1596
  /** The song's MP3 when `file` is one of the label's music videos (it holds the tags, cover and words); else `file`. */
1524
1597
  audioFor(file: string): string {
1525
1598
  if (!file.endsWith(".mp4")) return file;
@@ -1566,6 +1639,18 @@ export class AiLabel {
1566
1639
  }, null, 2)}\n`) });
1567
1640
  }
1568
1641
  if (entries.length === 0) return null;
1642
+ // Everything by an artist comes with who they are: the band's page, each member's page and portrait.
1643
+ if (scope.kind === "artist") {
1644
+ const folder = this.folderOf(artist);
1645
+ const exists = (path: string): boolean => { try { return statSync(path).isFile(); } catch { return false; } };
1646
+ if (exists(join(folder, "artist.md"))) entries.push({ name: `${top}/artist.md`, path: join(folder, "artist.md") });
1647
+ for (const slug of artist.members ?? []) {
1648
+ for (const ext of ["md", "jpg"]) {
1649
+ const path = join(folder, "members", `${slug}.${ext}`);
1650
+ if (exists(path)) entries.push({ name: `${top}/members/${slug}.${ext}`, path });
1651
+ }
1652
+ }
1653
+ }
1569
1654
  const what = scope.kind === "artist" ? "Discography" : scope.kind === "album" ? albums[0]!.title : this.songFile(scope.artist, scope.album, scope.n) ? albums[0]!.songs.find((one) => one.n === scope.n)!.title : "Song";
1570
1655
  return { name: `${fileName(artist.name)} - ${fileName(what)}.zip`, entries };
1571
1656
  }
@@ -1582,5 +1667,7 @@ export interface PublicArtist {
1582
1667
  name: string;
1583
1668
  genre: string;
1584
1669
  bio: string;
1670
+ /** The people (profile pages at /api/v1/label/<artist>/members/<slug>.md, portraits .jpg). */
1671
+ members: Array<{ slug: string; name: string; role: string; bio: string }>;
1585
1672
  albums: Array<{ key: string; title: string; year: number; concept: string; cover: boolean; complete: boolean; songs: Array<{ n: number; title: string; seconds: number; lyrics: string }> }>;
1586
1673
  }
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Who is in each AI label band: an OpenProfile page per member and one for
3
+ * the band, so the same people sing, appear on covers and in videos every
4
+ * time instead of whoever an image model draws next.
5
+ *
6
+ * <artist folder>/artist.md the band: genre, sound, members, discography
7
+ * <artist folder>/members/<slug>.md a member: role, look, voice, personality...
8
+ * <artist folder>/members/<slug>.jpg their reference portrait
9
+ *
10
+ * The pages are the source of truth once written: a person may edit a
11
+ * member's look or voice by hand, and what is generated next reads the page
12
+ * back (readMember). Members are invented once, by a language model, as
13
+ * fictional people; the portrait is drawn from the look and kept.
14
+ */
15
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import type { askJson } from "./ai-text.ts";
18
+
19
+ export interface Member {
20
+ slug: string;
21
+ name: string;
22
+ /** What they do in the band: "lead vocals", "lead guitar", "drums"... */
23
+ role: string;
24
+ /** How they look, in enough detail to draw the same person again: age, face, hair, build, signature clothes. */
25
+ look: string;
26
+ /** How they sound, for a singer; how they play, for the rest. */
27
+ voice: string;
28
+ personality: string;
29
+ influences: string;
30
+ bio: string;
31
+ }
32
+
33
+ export function memberSlug(name: string): string {
34
+ return name.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "member";
35
+ }
36
+
37
+ function line(text: string): string {
38
+ return text.replace(/[\r\n]+/g, " ").trim();
39
+ }
40
+
41
+ /** A member's OpenProfile page. */
42
+ export function memberMarkdown(member: Member, band: { name: string; holder: string }): string {
43
+ return [
44
+ `# ${member.name}`,
45
+ "",
46
+ "- **Kind**: fictional musician, made with AI",
47
+ `- **Band**: [${band.name}](../artist.md)`,
48
+ `- **Role**: ${line(member.role)}`,
49
+ `- **Avatar**: [portrait](${member.slug}.jpg)`,
50
+ `- **Parent**: ${band.holder}`,
51
+ "",
52
+ line(member.bio),
53
+ "",
54
+ "## Look",
55
+ "",
56
+ line(member.look),
57
+ "",
58
+ "## Voice",
59
+ "",
60
+ line(member.voice),
61
+ "",
62
+ "## Personality",
63
+ "",
64
+ line(member.personality),
65
+ "",
66
+ "## Influences",
67
+ "",
68
+ line(member.influences),
69
+ "",
70
+ ].join("\n");
71
+ }
72
+
73
+ /** A member's page read back, so hand edits win; null when it is not one of ours. */
74
+ export function readMember(text: string, slug: string): Member | null {
75
+ const name = /^#\s+(.+)$/m.exec(text)?.[1]?.trim() ?? "";
76
+ if (!name) return null;
77
+ const field = (label: string): string => new RegExp(`^- \\*\\*${label}\\*\\*:\\s*(.+)$`, "m").exec(text)?.[1]?.trim() ?? "";
78
+ const section = (heading: string): string => {
79
+ const match = new RegExp(`^##\\s+${heading}\\s*$([\\s\\S]*?)(?=^##\\s|$(?![\\s\\S]))`, "m").exec(text);
80
+ return (match?.[1] ?? "").trim().replace(/\s+/g, " ");
81
+ };
82
+ // The bio is the prose between the fields and the first section.
83
+ const bio = (/^- \*\*Parent\*\*:.*$\n+([\s\S]*?)(?=^##\s)/m.exec(text)?.[1] ?? "").trim().replace(/\s+/g, " ");
84
+ return { slug, name, role: field("Role"), look: section("Look"), voice: section("Voice"), personality: section("Personality"), influences: section("Influences"), bio };
85
+ }
86
+
87
+ /** The band's OpenProfile page. */
88
+ export function bandMarkdown(band: {
89
+ name: string; genre: string; sound: string; voice: string; bio: string; themes: string; holder: string;
90
+ members: Member[]; albums: Array<{ year: number; title: string }>;
91
+ }): string {
92
+ return [
93
+ `# ${band.name}`,
94
+ "",
95
+ "- **Kind**: band, fictional, made with AI",
96
+ `- **Genre**: ${band.genre}`,
97
+ `- **Label**: ${band.holder}`,
98
+ `- **Members**: ${band.members.map((one) => `[${one.name}](members/${one.slug}.md) (${one.role})`).join(", ")}`,
99
+ "",
100
+ line(band.bio),
101
+ "",
102
+ "## Sound",
103
+ "",
104
+ line(band.sound),
105
+ "",
106
+ "## Lead voice",
107
+ "",
108
+ line(band.voice),
109
+ "",
110
+ "## Themes",
111
+ "",
112
+ line(band.themes),
113
+ "",
114
+ "## Discography",
115
+ "",
116
+ ...(band.albums.length ? band.albums.map((one) => `- ${one.year} · ${one.title}`) : ["- (first album on its way)"]),
117
+ "",
118
+ ].join("\n");
119
+ }
120
+
121
+ const MEMBERS_SYSTEM = [
122
+ "You cast the members of a fictional band (or the one person behind a solo act) for an AI record label.",
123
+ "Everyone is invented: never a real person, never a lookalike of one. Give each a full name, their role, and a look described",
124
+ "precisely enough that an illustrator could draw the same person every time: age range, face, skin tone, hair, build, signature outfit and accessories.",
125
+ "Answer as JSON: {\"members\": [{\"name\": \"\", \"role\": \"\", \"look\": \"at most 300 characters\", \"voice\": \"how they sing or play, at most 150 characters\",",
126
+ "\"personality\": \"at most 150 characters\", \"influences\": \"styles and eras, never named artists, at most 120 characters\", \"bio\": \"one or two sentences\"}]}.",
127
+ ].join(" ");
128
+
129
+ /** The band's people, invented once: one for a solo act, three to five for a band. */
130
+ export async function inventMembers(
131
+ band: { name: string; genre: string; sound: string; voice: string; bio: string },
132
+ ask: typeof askJson,
133
+ ): Promise<Member[]> {
134
+ const answer = await ask({
135
+ system: MEMBERS_SYSTEM,
136
+ prompt: [
137
+ `Act: ${band.name} (${band.genre})`,
138
+ `Sound: ${band.sound}`,
139
+ `Lead voice: ${band.voice}`,
140
+ band.bio ? `Who they are: ${band.bio}` : "",
141
+ "If the name reads as one person's, cast that one person as the solo artist (role: vocals and the instrument that fits); otherwise cast the band, the lead singer first, matching the lead voice.",
142
+ ].filter(Boolean).join("\n"),
143
+ maxTokens: 2000,
144
+ timeoutMs: 90_000,
145
+ });
146
+ const list = Array.isArray(answer.value["members"]) ? answer.value["members"] as Array<Record<string, unknown>> : [];
147
+ const seen = new Set<string>();
148
+ const members = list
149
+ .map((one) => {
150
+ const name = line(String(one?.["name"] ?? "")).slice(0, 60);
151
+ return {
152
+ slug: memberSlug(name), name,
153
+ role: line(String(one?.["role"] ?? "")).slice(0, 80),
154
+ look: line(String(one?.["look"] ?? "")).slice(0, 500),
155
+ voice: line(String(one?.["voice"] ?? "")).slice(0, 300),
156
+ personality: line(String(one?.["personality"] ?? "")).slice(0, 300),
157
+ influences: line(String(one?.["influences"] ?? "")).slice(0, 200),
158
+ bio: line(String(one?.["bio"] ?? "")).slice(0, 500),
159
+ };
160
+ })
161
+ .filter((one) => one.name && one.look.length > 20 && !seen.has(one.slug) && seen.add(one.slug))
162
+ .slice(0, 6);
163
+ if (members.length === 0) throw new Error("the model cast nobody");
164
+ return members;
165
+ }
166
+
167
+ /** How the band looks on stage, for a cover or a scene: every member by name, role and look. */
168
+ export function castLine(members: Member[]): string {
169
+ return members.map((one) => `${one.name} (${one.role}): ${one.look}`).join("; ");
170
+ }
171
+
172
+ /** The portrait prompt for a member: the same person every time it is used as a reference. */
173
+ export function portraitPrompt(member: Member, band: { name: string; genre: string }): string {
174
+ return `Photographic portrait of ${member.look}. ${member.role} in the ${band.genre} band ${band.name}. Head and shoulders, three-quarter view, natural expression, soft studio light, plain dark background, sharp focus, 85mm lens. No text, no logos.`;
175
+ }
176
+
177
+ /** Writes the member pages and portraits that are missing; returns the members as the pages now say. */
178
+ export async function writeMembers(folder: string, members: Member[], band: { name: string; genre: string; holder: string }, draw: ((prompt: string) => Promise<Buffer | null>) | null): Promise<Member[]> {
179
+ const dir = join(folder, "members");
180
+ mkdirSync(dir, { recursive: true });
181
+ const out: Member[] = [];
182
+ for (const member of members) {
183
+ const page = join(dir, `${member.slug}.md`);
184
+ let current = member;
185
+ try {
186
+ current = readMember(readFileSync(page, "utf8"), member.slug) ?? member;
187
+ } catch {
188
+ writeFileSync(page, memberMarkdown(member, band));
189
+ }
190
+ const portrait = join(dir, `${member.slug}.jpg`);
191
+ let drawn = true;
192
+ try { readFileSync(portrait); } catch { drawn = false; }
193
+ if (!drawn && draw) {
194
+ const picture = await draw(portraitPrompt(current, band)).catch(() => null);
195
+ if (picture) writeFileSync(portrait, picture);
196
+ }
197
+ out.push(current);
198
+ }
199
+ return out;
200
+ }
201
+
202
+ /** The members as their pages say now (hand edits included), in the order given. */
203
+ export function readMembers(folder: string, slugs: string[]): Member[] {
204
+ return slugs.flatMap((slug) => {
205
+ try {
206
+ const member = readMember(readFileSync(join(folder, "members", `${slug}.md`), "utf8"), slug);
207
+ return member ? [member] : [];
208
+ } catch {
209
+ return [];
210
+ }
211
+ });
212
+ }
@@ -20,9 +20,12 @@ import { adCsp, withPageAd, type GuideAds } from "./station-guide.ts";
20
20
  // MP3 or a zip needs a grant from nixamp.com's store (music-store.ts).
21
21
  const FILE = /^\/api\/v1\/label\/([a-f0-9]{10})\/([a-f0-9]{8})\/(\d{1,3}\.(?:txt|mp3)|cover\.jpg)$/;
22
22
 
23
+ /** An artist's OpenProfile pages and portraits: artist.md, members/<slug>.md, members/<slug>.jpg. */
24
+ const PROFILE = /^\/api\/v1\/label\/([a-f0-9]{10})\/(artist\.md|members\/[a-z0-9-]{1,40}\.(?:md|jpg))$/;
25
+
23
26
  /** Whether this path is the label's public face (an MP3 or the zip still asks for its grant). */
24
27
  export function isPublicLabelPath(path: string): boolean {
25
- return path === "/label" || path === "/api/v1/label" || path === "/api/v1/label/zip" || FILE.test(path);
28
+ return path === "/label" || path === "/api/v1/label" || path === "/api/v1/label/zip" || FILE.test(path) || PROFILE.test(path);
26
29
  }
27
30
 
28
31
  /** nixamp.com's page that sells this: a song, an album or everything by the artist. */
@@ -146,6 +149,16 @@ export async function handleLabelRoutes(
146
149
  response.end();
147
150
  return true;
148
151
  }
152
+ const profile = PROFILE.exec(path);
153
+ if (profile) {
154
+ const found = label.profileFile(profile[1]!, profile[2]!);
155
+ if (!found) {
156
+ ctx.json(response, 404, { error: "no such profile", code: "not_found" });
157
+ return true;
158
+ }
159
+ sendFile(request, response, found.path, found.type, "");
160
+ return true;
161
+ }
149
162
  const [, artist, album, what] = FILE.exec(path)!;
150
163
  if (what!.endsWith(".mp3")) {
151
164
  const scope = ctx.grants && grant ? await ctx.grants.check(grant) : null;
@@ -270,6 +283,11 @@ audio{width:100%;max-width:360px;height:36px}
270
283
  details{margin-top:4px}summary{cursor:pointer;color:var(--muted);font-size:.9rem}
271
284
  pre.lyrics{white-space:pre-wrap;font:inherit;font-size:.95rem;margin:8px 0 0;padding:12px;border-radius:8px;background:var(--bg)}
272
285
  .dl{font-size:.85rem}.soon{color:var(--muted);font-size:.85rem}
286
+ ul.members{list-style:none;margin:12px 0 4px;padding:0;display:flex;flex-wrap:wrap;gap:10px}
287
+ ul.members a{display:flex;gap:8px;align-items:center;color:var(--fg);text-decoration:none;border:1px solid var(--line);border-radius:999px;padding:4px 12px 4px 4px}
288
+ ul.members a:hover,ul.members a:focus-visible{border-color:var(--accent)}
289
+ ul.members img{width:40px;height:40px;border-radius:50%;object-fit:cover;background:var(--line)}
290
+ ul.members span{display:grid;line-height:1.2}ul.members .role{color:var(--muted);font-size:.8rem}
273
291
  a.buy{display:inline-block;font-weight:700;text-decoration:none;border:1px solid var(--accent);border-radius:999px;padding:2px 10px}
274
292
  footer{margin-top:48px;color:var(--muted);font-size:.85rem}footer a{color:inherit}
275
293
  `;
@@ -285,6 +303,16 @@ export const LABEL_CSP = [
285
303
 
286
304
  type Shop = { site: string; server: string } | undefined;
287
305
 
306
+ /** The band: each member's portrait, name and role, linking to their OpenProfile page. */
307
+ function renderMembers(artist: PublicArtist): string {
308
+ if (!artist.members?.length) return "";
309
+ const base = `/api/v1/label/${artist.key}`;
310
+ return `<ul class="members">${artist.members.map((member) => `<li><a href="${base}/members/${escape(member.slug)}.md" title="${escape(member.bio)}">`
311
+ + `<img src="${base}/members/${escape(member.slug)}.jpg" alt="" width="56" height="56" loading="lazy">`
312
+ + `<span><strong>${escape(member.name)}</strong><span class="role">${escape(member.role)}</span></span></a></li>`).join("")}</ul>`
313
+ + `<p class="dl"><a href="${base}/artist.md">${escape(artist.name)}'s profile</a></p>`;
314
+ }
315
+
288
316
  function price(cents: number): string {
289
317
  return cents < 100 ? `${cents}¢` : `$${(cents / 100).toFixed(cents % 100 ? 2 : 0)}`;
290
318
  }
@@ -313,7 +341,7 @@ export function renderLabel(view: ReturnType<AiLabel["publicView"]>, shop?: Shop
313
341
  const nav = view.genres.length > 1 ? `<nav class="genres" aria-label="Genres">${view.genres.map((one) => `<a href="#${escape(one.genre.toLowerCase().replace(/[^a-z0-9]+/g, "-"))}">${escape(one.genre)}</a>`).join("")}</nav>` : "";
314
342
  const sections = view.genres.map((genre) => `<section class="genre" id="${escape(genre.genre.toLowerCase().replace(/[^a-z0-9]+/g, "-"))}" aria-labelledby="g-${escape(genre.genre.toLowerCase().replace(/[^a-z0-9]+/g, "-"))}">`
315
343
  + `<h2 id="g-${escape(genre.genre.toLowerCase().replace(/[^a-z0-9]+/g, "-"))}">${escape(genre.genre)}${genre.station ? ` <a href="/watch/${escape(genre.station)}">Listen live, free →</a>` : ""}</h2>`
316
- + genre.artists.map((artist) => `<article class="artist"><h3>${escape(artist.name)}</h3>${artist.bio ? `<p class="bio">${escape(artist.bio)}</p>` : ""}`
344
+ + genre.artists.map((artist) => `<article class="artist"><h3>${escape(artist.name)}</h3>${artist.bio ? `<p class="bio">${escape(artist.bio)}</p>` : ""}${renderMembers(artist)}`
317
345
  + `${shop ? `<p>${buy(shop, "artist", artist.key, "", 0, "everything by them")}</p>` : ""}`
318
346
  + `${artist.albums.map((album) => renderAlbum(artist, album, shop)).join("")}</article>`).join("")
319
347
  + `</section>`).join("");