@jonandev/longbeard 0.13.0 → 0.14.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 (55) hide show
  1. package/AGENTS.md +5 -5
  2. package/CHANGELOG.md +27 -0
  3. package/README.md +3 -4
  4. package/beard.json +6 -17
  5. package/bin/long-beard.js +2 -2
  6. package/package.json +1 -1
  7. package/skills/design/SKILL.md +4 -6
  8. package/skills/design-brief/SKILL.md +5 -5
  9. package/skills/design-check/SKILL.md +1 -1
  10. package/skills/design-check/references/design-rules.md +26 -4
  11. package/skills/design-check/scripts/rules.mjs +143 -9
  12. package/skills/design-direction/SKILL.md +70 -52
  13. package/skills/design-direction/references/design-floor.md +118 -0
  14. package/skills/design-direction/references/graphic.md +5 -6
  15. package/skills/design-direction/references/library.md +6 -6
  16. package/skills/design-direction/references/screen-template.html +2 -2
  17. package/skills/design-direction/references/subject.md +2 -2
  18. package/skills/design-direction/references/variants.js +43 -0
  19. package/skills/design-direction/scripts/canvas.mjs +12 -9
  20. package/skills/design-direction/scripts/colours.mjs +247 -0
  21. package/skills/design-direction/scripts/moodboard.mjs +1 -1
  22. package/skills/design-direction/scripts/rules.mjs +747 -0
  23. package/skills/design-direction/scripts/sheet.mjs +3 -1
  24. package/skills/design-figma/SKILL.md +1 -1
  25. package/skills/design-identity/SKILL.md +9 -7
  26. package/skills/design-identity/references/design-floor.md +118 -0
  27. package/skills/design-identity/scripts/colours.mjs +35 -1
  28. package/skills/design-identity/scripts/sheet.mjs +3 -1
  29. package/skills/design-moodboard/SKILL.md +6 -2
  30. package/skills/design-moodboard/references/graphic.md +1 -1
  31. package/skills/design-moodboard/scripts/group.mjs +1 -1
  32. package/skills/design-moodboard/scripts/moodboard.mjs +1 -1
  33. package/skills/design-prototype/SKILL.md +51 -48
  34. package/skills/design-prototype/references/design-floor.md +118 -0
  35. package/skills/design-prototype/references/design-md-template.md +3 -1
  36. package/skills/design-prototype/references/graphic.md +6 -5
  37. package/skills/design-prototype/references/variants.js +43 -0
  38. package/skills/design-prototype/scripts/links.mjs +5 -4
  39. package/skills/design-prototype/scripts/rules.mjs +143 -9
  40. package/skills/design-prototype/scripts/sheet.mjs +3 -1
  41. package/skills/design-wordmark/SKILL.md +6 -2
  42. package/skills/design-wordmark/scripts/sheet.mjs +3 -1
  43. package/skills/idea/SKILL.md +3 -3
  44. package/skills/design-direction/references/design-rules.md +0 -204
  45. package/skills/design-direction/references/full-build.md +0 -20
  46. package/skills/design-direction/references/grid.md +0 -97
  47. package/skills/design-direction/scripts/layout-diff.mjs +0 -118
  48. package/skills/design-families/SKILL.md +0 -139
  49. package/skills/design-families/scripts/contact-sheet.mjs +0 -259
  50. package/skills/design-families/scripts/families.mjs +0 -607
  51. package/skills/design-families/scripts/measure.mjs +0 -1728
  52. package/skills/design-families/scripts/moodboard.mjs +0 -609
  53. package/skills/design-families/scripts/tag.mjs +0 -289
  54. package/skills/design-prototype/references/design-rules.md +0 -204
  55. package/skills/design-prototype/references/five-second.md +0 -46
@@ -1,607 +0,0 @@
1
- #!/usr/bin/env node
2
- // Propose families from what is known about each reference, so a pool is
3
- // sorted on the same terms for every keep and the eye only splits, merges,
4
- // moves and names. No dependencies.
5
- //
6
- // node families.mjs .longbeard/design/<step>/profiles.json --board .longbeard/design/<step>/board.md
7
- // node families.mjs traits.tsv [--links links.tsv --pages traits-pages.tsv]
8
- //
9
- // profiles.json (measure.mjs --profiles, tags from tag.mjs) is the full read of
10
- // each reference. Only the look layer of tag.mjs (profile.tags) is sorted on;
11
- // the about layer (profile.about: format, domain, mood, hue, density) is what a
12
- // reference is for, kept for picking references for a brief, and never read here. A TSV from measure.mjs --tsv, with its live pages joined by
13
- // --links and --pages, is read the same way with what it has.
14
- //
15
- // How two references are compared. Each kind of trait gives a distance from 0
16
- // (the same) to 1 (as far apart as it goes): a number by its difference, the
17
- // 6 by 4 grid of where things sit by its average cell, a tag field by how much
18
- // the two sets of words differ. The distance between two references is the
19
- // larger of the weighted root mean square over the kinds both have, and 0.7
20
- // of the widest gap on a primary trait (how empty, how loud, how big the type,
21
- // where things sit, what the picture is, the layout), so one strong difference
22
- // is never averaged away: a reference with no tags, or no live page,
23
- // is compared on what it has, never placed in the middle. Tag every reference
24
- // before sorting: an untagged one is close to anything its numbers match, and
25
- // can join groups the tags would keep apart. It is named when it happens. The
26
- // measured traits hold about two thirds of the weight and the tags one third,
27
- // so the agent's eye steers the families without deciding them. The weights
28
- // are in WEIGHTS below, in plain sight.
29
- //
30
- // How families form. Every reference starts alone; the two closest groups (by
31
- // the average distance between their members) join, and joining stops when the
32
- // closest two are more than --spread apart (0.52 by default, on the 0 to 1
33
- // scale). How many families comes from the pool. What is still alone, or only
34
- // in a pair, is a stray: a pair is named as the seed of a family. A family
35
- // under six is too small to be a look of its own and is marked small. Two shots of one site
36
- // (the same link: site.jpg and site-menu.jpg) are one reference, its first
37
- // shot leading and the rest kept beside it as `also`.
38
- //
39
- // It writes families.json beside its input, one label<TAB>shot list per family
40
- // in families/ (for contact-sheet.mjs --contain), prints one line per family
41
- // with what its tags agree on, the pairs and each stray's nearest family, how
42
- // many families a slightly lower and higher --spread would give, and the
43
- // near-blank shots. --board writes a board.md skeleton: one card per
44
- // reference in its family, most typical first, pairs as their own groups.
45
- //
46
- // --sliders "loud=2,picture=4,rich=3,cool=2" places each family on the
47
- // sliders they answered in the first questions (playful and new are skipped:
48
- // the eye judges those), 1 to 5: quiet (1) to loud (5), airy (1) to dense (5),
49
- // type-led to picture-led, plain to rich, warm to cool. Each reference's place
50
- // comes from what is already measured and tagged, never from the eye; a
51
- // family's is its members' median. Each family's line then says whether it
52
- // sits near what they asked or is off on a slider: a hint for the families
53
- // board, never a cut. The whole pool is placed too: it is what they chose or
54
- // liked, and where it sits far from what they said is worth one question.
55
- //
56
- // --only families/f3.tsv sorts one family's members alone, to split a bin: a
57
- // family far bigger than the rest, where the pool's spread was too coarse. Pass
58
- // a lower --spread with it. It writes to families/f3-split/ (families.json and
59
- // one list per new family), so the pool's own families stay as they are.
60
- // --only also takes names: --only "card-12,card-40,card-41".
61
- //
62
- // --assign families.json adds new references to families that already exist, for a library that
63
- // grows: nothing already in a family moves. families.json is a previous run's output, or any
64
- // { families: [{ id, members: [shot or name] }] }; its strays are passed over and it is never
65
- // changed. Every reference in profiles.json in no family is new. Each is compared with each family
66
- // by its average distance to the members (the linkage families join by) and joins the nearest when
67
- // that is within --spread, with a confidence from 0 to 1: half how far inside the spread it sits,
68
- // half how much nearer that family is than the next. The new references that join nothing are
69
- // sorted among themselves: a group of --min or more is a seed, a proposed new family; the rest are
70
- // strays, with their nearest family. Each lists its 5 nearest references already in a family. Shots
71
- // of one site are not folded, and bins are not split. It writes assign.json beside the input (or
72
- // --out). It needs profiles.json, and does not go with --only, --board or --sliders.
73
- //
74
- // node families.mjs .longbeard/design/families/profiles.json --assign .longbeard/design/families/families.json
75
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
76
- import { basename, dirname, extname, join, relative, resolve } from "node:path";
77
-
78
- const args = process.argv.slice(2);
79
- const flag = (name, def) => {
80
- const i = args.indexOf(`--${name}`);
81
- return i === -1 ? def : (args.splice(i, 2)[1] ?? "");
82
- };
83
- const spreadArg = flag("spread", "");
84
- const min = Number(flag("min", "3"));
85
- const boardArg = flag("board", "");
86
- const linksArg = flag("links", "");
87
- const outArg = flag("out", "");
88
- const pagesArg = flag("pages", "");
89
- const slidersArg = flag("sliders", "");
90
- const onlyArg = flag("only", "");
91
- const assignArg = flag("assign", "");
92
- const [input] = args;
93
- const usage = "usage: node families.mjs profiles.json | traits.tsv [--only families/f3.tsv | name,name] [--spread 0.52] [--min 3] [--board board.md] [--links links.tsv] [--pages traits-pages.tsv] [--out families.json] [--sliders loud=2,picture=4,rich=3,cool=2]\n node families.mjs profiles.json --assign families.json [--spread 0.52] [--min 3] [--out assign.json]";
94
- if (!input || args.length !== 1 || (spreadArg && !(Number(spreadArg) > 0 && Number(spreadArg) < 1)) || !(Number.isInteger(min) && min >= 1)) {
95
- console.error(usage);
96
- process.exit(2);
97
- }
98
- const fail = (text) => {
99
- console.error(`families: ${text}`);
100
- process.exit(1);
101
- };
102
- if (!existsSync(input)) fail(`nothing at ${input}`);
103
- if (assignArg) {
104
- const clash = [onlyArg && "--only", boardArg && "--board", slidersArg && "--sliders"].filter(Boolean);
105
- if (clash.length) fail(`--assign does not go with ${clash.join(", ")}: it only adds new references to the families there are`);
106
- if (!/\.json$/i.test(input)) fail("--assign needs profiles.json (measure.mjs --profiles), not a TSV");
107
- if (!existsSync(assignArg)) fail(`no families at ${assignArg}`);
108
- }
109
- const spread = spreadArg ? Number(spreadArg) : 0.52;
110
-
111
- // ------------------------------------------------------------------ read the references
112
- const readTsv = (path) => {
113
- const [head, ...rows] = readFileSync(path, "utf8").trim().split(/\r?\n/).map((l) => l.split("\t"));
114
- return rows.map((r) => Object.fromEntries(head.map((name, i) => [name, r[i]])));
115
- };
116
- const links = new Map();
117
- if (linksArg) {
118
- if (!existsSync(linksArg)) fail(`no links at ${linksArg}`);
119
- for (const l of readFileSync(linksArg, "utf8").split(/\r?\n/)) {
120
- const [name, link] = l.split("\t");
121
- if (name && link) links.set(name.trim(), link.trim());
122
- }
123
- }
124
- const nameOfShot = (shot) => basename(shot, extname(shot));
125
- const num = (v) => (v === undefined || v === null || v === "" ? null : Number(v));
126
-
127
- let refs;
128
- if (/\.json$/i.test(input)) {
129
- const store = JSON.parse(readFileSync(input, "utf8")).refs || {};
130
- // A profile with no shot or no read of its picture cannot be compared: it is named, never dropped quietly.
131
- const readable = ([, p]) => p && p.shot && p.image?.traits;
132
- const unread = Object.entries(store).filter((e) => !readable(e)).map(([name]) => name);
133
- if (unread.length) console.error(`families: left out, no picture read in ${input} (measure them again): ${unread.join(", ")}`);
134
- refs = Object.entries(store)
135
- .filter(readable)
136
- .map(([name, p]) => ({ name, shot: p.shot, link: p.link || null, image: p.image.traits, figure: p.image.figure || null, page: p.page?.flag ? null : p.page?.traits || null, media: p.page?.flag ? null : p.page?.media || null, flag: p.page?.flag || "", tags: p.tags || null }));
137
- } else {
138
- const pages = new Map();
139
- if (pagesArg) {
140
- if (!linksArg) fail("--pages needs --links, to know which page belongs to which picture");
141
- if (!existsSync(pagesArg)) fail(`no page traits at ${pagesArg}`);
142
- for (const row of readTsv(pagesArg)) pages.set(row.ref, row);
143
- }
144
- refs = readTsv(input).map((row) => {
145
- for (const k of ["ref", "lum", "empty", "loud", "busy"]) if (!(k in row)) fail(`the TSV has no ${k} column: make it with measure.mjs --tsv`);
146
- const name = row.name || nameOfShot(row.ref);
147
- const link = links.get(name) || links.get(basename(row.ref)) || links.get(row.ref) || null;
148
- const page = link ? pages.get(link) || null : null;
149
- return { name, shot: row.ref, link, image: row, figure: null, page: page?.flag ? null : page, media: null, flag: page?.flag || "", tags: null };
150
- });
151
- }
152
- let onlyLabel = "";
153
- if (onlyArg) {
154
- const names = existsSync(onlyArg)
155
- ? readFileSync(onlyArg, "utf8").split(/\r?\n/).map((l) => l.split("\t")[0].trim()).filter(Boolean)
156
- : onlyArg.split(",").map((x) => x.trim()).filter(Boolean);
157
- const wanted = new Set(names);
158
- const missing = names.filter((n) => !refs.some((r) => r.name === n));
159
- if (missing.length) fail(`--only names ${missing.length} not in ${input}: ${missing.slice(0, 5).join(", ")}${missing.length > 5 ? " …" : ""}`);
160
- refs = refs.filter((r) => wanted.has(r.name));
161
- onlyLabel = existsSync(onlyArg) ? basename(onlyArg, extname(onlyArg)) : "only";
162
- }
163
- if (refs.length < 2) fail("fewer than two references to sort");
164
-
165
- // ------------------------------------------------------------------ the sliders they answered
166
- // Each 1 to 5, from what is measured and tagged. null where nothing says.
167
- const SLIDERS = {
168
- loud: ["quiet", "loud"],
169
- picture: ["type-led", "picture-led"],
170
- rich: ["plain", "rich"],
171
- cool: ["warm", "cool"],
172
- dense: ["airy", "dense"],
173
- };
174
- // playful and new, also on the design brief, are not read from a picture: the eye judges those.
175
- const UNMEASURED = new Set(["playful", "new"]);
176
- const asked = {};
177
- for (const part of slidersArg.split(",").map((x) => x.trim()).filter(Boolean)) {
178
- const [key, value] = part.split("=").map((x) => x.trim());
179
- if (UNMEASURED.has(key)) continue;
180
- if (!SLIDERS[key] || !(Number(value) >= 1 && Number(value) <= 5)) fail(`--sliders ${part}: use ${Object.keys(SLIDERS).join(", ")}, each 1 to 5 (${Object.entries(SLIDERS).map(([k, [a, b]]) => `${k}: 1 ${a}, 5 ${b}`).join("; ")})`);
181
- asked[key] = Number(value);
182
- }
183
- const mean = (xs) => (xs.filter((x) => x !== null).length ? xs.filter((x) => x !== null).reduce((t, x) => t + x, 0) / xs.filter((x) => x !== null).length : null);
184
- const to5 = (x) => 1 + 4 * Math.min(1, Math.max(0, x));
185
- // Hue in degrees and chroma (how far the colour is from grey, 0 to 1). Not HSL saturation, which
186
- // reads an off-white as strongly coloured: a ground of #f1ede4 has a chroma of 0.05, not 0.3.
187
- const hueChroma = (hex) => {
188
- const [r, g, b] = [1, 3, 5].map((i) => parseInt(String(hex).slice(i, i + 2), 16) / 255);
189
- if ([r, g, b].some(Number.isNaN)) return null;
190
- const mx = Math.max(r, g, b), mn = Math.min(r, g, b), d = mx - mn;
191
- if (!d) return [0, 0];
192
- const h = mx === r ? ((g - b) / d + 6) % 6 : mx === g ? (b - r) / d + 2 : (r - g) / d + 4;
193
- return [h * 60, d];
194
- };
195
- const PICTURE_PLACE = { none: 0, lettering: 0, ui: 0.5, icon: 0.5, shape: 0.5, pattern: 0.5, photo: 1, render: 1, illustration: 1, collage: 1, product: 1 };
196
- const COLOUR_PLACE = { neutral: 0, muted: 0.25, "one-accent": 0.4, bright: 0.75, multi: 1 };
197
- function placeOf(r) {
198
- const empty = num(r.image.empty), loud = num(r.image.loud);
199
- const pic = r.tags?.picture?.[0], col = r.tags?.colour?.[0];
200
- // Warm or cool: the ground and the figure's palette, each colour by its share and its chroma.
201
- const swatches = [[r.image.ground, empty ?? 0], ...(r.figure?.palette || []).map((c) => [c.colour, ((100 - (empty ?? 0)) * c.share) / 100])];
202
- let warm = 0, cool = 0, all = 0;
203
- for (const [hex, share] of swatches) {
204
- const hs = hex && hueChroma(hex);
205
- if (!hs) continue;
206
- const w = share * hs[1];
207
- all += share;
208
- if (hs[0] < 75 || hs[0] >= 330) warm += w;
209
- else if (hs[0] >= 150 && hs[0] < 270) cool += w;
210
- }
211
- return {
212
- loud: empty === null ? null : to5(0.45 * (1 - empty / 100) + 0.55 * Math.min(1, (loud ?? 0) / 25)),
213
- picture: mean([pic in PICTURE_PLACE ? to5(PICTURE_PLACE[pic]) : null, r.page && has(r.page.pictures) ? to5(num(r.page.pictures) / 60) : null]),
214
- rich: mean([col in COLOUR_PLACE ? to5(COLOUR_PLACE[col]) : null, r.figure?.colours ? to5(Math.log(Math.max(1, r.figure.colours)) / Math.log(200)) : null]),
215
- cool: all ? 3 + 2 * Math.max(-1, Math.min(1, (cool - warm) / (all * 0.25))) : null,
216
- // Dense: how little of the first screen is empty. 80% empty is airy (1), 20% is dense (5).
217
- dense: empty === null ? null : to5((80 - empty) / 60),
218
- };
219
- }
220
-
221
- // Two shots of one site are one reference: the shortest name leads, the others ride along.
222
- // Not with --assign: there each shot is placed on its own.
223
- const byLink = new Map();
224
- if (!assignArg) for (const r of refs) if (r.link) byLink.set(r.link, [...(byLink.get(r.link) || []), r]);
225
- const also = new Map();
226
- for (const group of byLink.values()) {
227
- if (group.length < 2) continue;
228
- const [lead, ...rest] = [...group].sort((a, b) => a.name.length - b.name.length || a.name.localeCompare(b.name));
229
- also.set(lead.name, rest.map((r) => r.name));
230
- for (const r of rest) r.folded = true;
231
- }
232
- const folded = refs.filter((r) => r.folded).length;
233
- refs = refs.filter((r) => !r.folded);
234
-
235
- // ------------------------------------------------------------------ what is compared, and how much it counts
236
- // Each kind of trait: how to read it from a reference (null when it does not have it), how far two
237
- // readings are on 0 to 1, and its weight. Measured traits first; the agent's tags last.
238
- const VOCAB = (await import("./tag.mjs")).VOCABULARY;
239
- const clamp = (v) => Math.max(0, Math.min(1, v));
240
- const scalar = (read, weight) => ({ read, weight, dist: (a, b) => Math.abs(a - b) });
241
- const sizeOf = (display) => {
242
- const px = parseFloat(display);
243
- // 12 px reads as 0, 200 px and over as 1, on a log scale: 24 to 48 px is as far as 48 to 96 px.
244
- return px > 0 ? clamp(Math.log2(px / 12) / Math.log2(200 / 12)) : null;
245
- };
246
- const tagField = (field, weight) => ({
247
- read: (r) => {
248
- const words = r.tags?.[field];
249
- if (!words || !words.length) return null;
250
- // The main word counts twice the second: a distribution over the field's words.
251
- const w = words.map((_, i) => (i === 0 ? 2 : 1));
252
- const total = w.reduce((t, v) => t + v, 0);
253
- return Object.fromEntries(words.map((word, i) => [word, w[i] / total]));
254
- },
255
- weight,
256
- // How much the two sets of words differ: 0 the same, 1 nothing shared.
257
- dist: (a, b) => 0.5 * [...new Set([...Object.keys(a), ...Object.keys(b)])].reduce((t, k) => t + Math.abs((a[k] || 0) - (b[k] || 0)), 0),
258
- });
259
- const has = (v) => v !== undefined && v !== null && v !== "";
260
- const WEIGHTS = {
261
- // From the picture: what a person sees from across a room.
262
- light: scalar((r) => clamp(Math.cbrt(num(r.image.lum) ?? 0.5)), 0.5),
263
- empty: scalar((r) => clamp((num(r.image.empty) ?? 50) / 100), 1),
264
- loud: scalar((r) => clamp(Math.sqrt((num(r.image.loud) ?? 0) / 100)), 1),
265
- busy: scalar((r) => clamp((num(r.image.busy) ?? 0) / 20), 0.7),
266
- // What the picture is made of, read on the figure (everything but the ground).
267
- colours: scalar((r) => (r.figure ? clamp(Math.log2(r.figure.colours + 1) / 9) : null), 0.6),
268
- colourful: scalar((r) => (r.figure ? clamp(r.figure.colourful / 150) : null), 0.6),
269
- grey: scalar((r) => (r.figure ? r.figure.grey / 100 : null), 0.5),
270
- soft: scalar((r) => (r.figure ? r.figure.soft / 100 : null), 0.6),
271
- sharp: scalar((r) => (r.figure ? r.figure.sharp / 100 : null), 0.6),
272
- where: { read: (r) => (r.figure?.grid?.length === 24 ? r.figure.grid.map((v) => v / 100) : null), weight: 1, dist: (a, b) => a.reduce((t, v, i) => t + Math.abs(v - b[i]), 0) / a.length },
273
- // From the live page, when there is one.
274
- "type size": scalar((r) => (r.page ? sizeOf(r.page.display) : null), 1),
275
- pictures: scalar((r) => (r.page && has(r.page.pictures) ? clamp(num(r.page.pictures) / 100) : null), 0.7),
276
- gradient: scalar((r) => (r.page && has(r.page.gradient) ? clamp(num(r.page.gradient) / 100) : null), 0.5),
277
- centred: scalar((r) => (r.page?.align ? (r.page.align === "centre" ? 1 : 0) : null), 0.5),
278
- "solid blocks": scalar((r) => (r.page && has(r.page.blocks) ? clamp(num(r.page.blocks) / 60) : null), 0.5),
279
- icons: scalar((r) => (r.page && has(r.page.icons) ? clamp(Math.log2(num(r.page.icons) + 1) / 5) : null), 0.4),
280
- "video or canvas": scalar((r) => (r.media ? clamp(((r.media.video || 0) + (r.media.canvas || 0)) / 100) : null), 0.5),
281
- // The agent's eye, in the fixed vocabulary: about a third of the weight in all.
282
- picture: tagField("picture", 1.5),
283
- layout: tagField("layout", 1),
284
- scale: tagField("scale", 0.8),
285
- type: tagField("type", 0.5),
286
- colour: tagField("colour", 0.5),
287
- surface: tagField("surface", 0.5),
288
- photo: tagField("photo", 0.3),
289
- weight: tagField("weight", 0.2),
290
- // Optional in a row: compared only between references that both have it.
291
- motion: tagField("motion", 0.4),
292
- };
293
- for (const field of Object.keys(VOCAB)) if (!WEIGHTS[field]) WEIGHTS[field] = tagField(field, 0.3);
294
- const kinds = Object.entries(WEIGHTS).filter(([, k]) => refs.some((r) => k.read(r) !== null));
295
- for (const r of refs) r.v = kinds.map(([, k]) => k.read(r));
296
-
297
- // What a person sees first from across a room. Two screens far apart on any one of these do not look
298
- // alike, however much else agrees: an empty page and a loud poster with the same tags; a photograph
299
- // and a drawing; small type and type that fills the screen. Light or dark is left out on purpose:
300
- // the same look on both grounds is one family.
301
- const PRIMARY = new Set(["empty", "loud", "type size", "where", "picture", "layout"]);
302
- const n = refs.length;
303
- const pairDist = (a, b) => {
304
- let total = 0, weight = 0, strongest = 0;
305
- for (const [i, [name, k]] of kinds.entries()) {
306
- const x = a.v[i], y = b.v[i];
307
- if (x === null || y === null) continue;
308
- const d = k.dist(x, y);
309
- total += k.weight * d * d;
310
- weight += k.weight;
311
- if (PRIMARY.has(name)) strongest = Math.max(strongest, d);
312
- }
313
- // The larger of the whole mix (a root mean square, so a kind far apart is not averaged away) and
314
- // the widest gap on a primary trait, at 0.7.
315
- return weight ? Math.max(Math.sqrt(total / weight), 0.7 * strongest) : 1;
316
- };
317
- const D = refs.map((a) => refs.map((b) => pairDist(a, b)));
318
-
319
- // ------------------------------------------------------------------ join, closest first
320
- // Over the whole pool, or over some of it (to split a bin).
321
- function cluster(cut, among = refs.map((_, i) => i)) {
322
- const m = among.length;
323
- const groups = among.map((i) => ({ members: [i], alive: true }));
324
- const link = among.map((a) => among.map((b) => D[a][b]));
325
- for (;;) {
326
- let best = Infinity, bi = -1, bj = -1;
327
- for (let i = 0; i < m; i++) {
328
- if (!groups[i].alive) continue;
329
- for (let j = i + 1; j < m; j++) if (groups[j].alive && link[i][j] < best) [best, bi, bj] = [link[i][j], i, j];
330
- }
331
- if (bi < 0 || best > cut) break;
332
- const [gi, gj] = [groups[bi], groups[bj]];
333
- for (let k = 0; k < m; k++) {
334
- if (!groups[k].alive || k === bi || k === bj) continue;
335
- link[bi][k] = link[k][bi] = (gi.members.length * link[bi][k] + gj.members.length * link[bj][k]) / (gi.members.length + gj.members.length);
336
- }
337
- gi.members.push(...gj.members);
338
- gj.alive = false;
339
- }
340
- return groups.filter((g) => g.alive).map((g) => g.members);
341
- }
342
-
343
- // ------------------------------------------------------------------ --assign: add new references to the families there are
344
- if (assignArg) {
345
- let prior;
346
- try {
347
- prior = JSON.parse(readFileSync(assignArg, "utf8"));
348
- } catch {
349
- fail(`${assignArg} is not JSON`);
350
- }
351
- // A member is named by its shot or its name.
352
- const indexOf = new Map();
353
- refs.forEach((r, i) => indexOf.set(r.name, i));
354
- refs.forEach((r, i) => indexOf.set(r.shot, i));
355
- const placed = new Set(), missing = [], fams = [];
356
- for (const f of prior?.families || []) {
357
- if (f.stray) continue;
358
- const members = [];
359
- for (const m of f.members || []) {
360
- const i = indexOf.get(m);
361
- if (i === undefined) missing.push(m);
362
- else if (!placed.has(i)) placed.add(i), members.push(i);
363
- }
364
- // Other shots of a site a full sort folded in are in the family too, though not compared.
365
- for (const names of Object.values(f.also || {})) for (const m of names) if (indexOf.has(m)) placed.add(indexOf.get(m));
366
- if (members.length) fams.push({ id: String(f.id), members });
367
- }
368
- if (!fams.length) fail(`${assignArg} has no family whose members are in ${input}`);
369
- const r2 = (x) => Math.round(x * 100) / 100;
370
- const inFamily = fams.flatMap((f) => f.members);
371
- const fresh = refs.map((_, i) => i).filter((i) => !placed.has(i));
372
- const read = (i) => {
373
- const ranked = fams.map((f) => ({ family: f.id, distance: f.members.reduce((t, j) => t + D[i][j], 0) / f.members.length })).sort((a, b) => a.distance - b.distance);
374
- const [first, second] = ranked;
375
- const nearest = [...inFamily].sort((a, b) => D[i][a] - D[i][b]).slice(0, 5).map((j) => ({ name: refs[j].name, distance: r2(D[i][j]) }));
376
- return { first, d2: second ? second.distance : null, second: second ? { family: second.family, distance: r2(second.distance) } : null, nearest };
377
- };
378
- const assigned = [], left = [], lines = [];
379
- for (const i of fresh) {
380
- const { first, d2, second, nearest } = read(i);
381
- if (first.distance > spread) {
382
- left.push(i);
383
- continue;
384
- }
385
- // Half how far inside the spread it sits, half how much nearer this family is than the next (all of it with one family).
386
- const d1 = first.distance;
387
- const margin = d2 === null ? 1 : d2 > 0 ? (d2 - d1) / d2 : 0;
388
- const confidence = r2(Math.max(0, Math.min(1, 0.5 * (1 - d1 / spread) + 0.5 * margin)));
389
- assigned.push({ name: refs[i].name, shot: refs[i].shot, family: first.family, distance: r2(d1), confidence, second, nearest_family: first.family, nearest });
390
- lines.push(`${refs[i].name} → ${first.family} distance ${r2(d1)} confidence ${confidence}${second ? ` (next ${second.family} ${second.distance})` : ""} near ${nearest.map((x) => x.name).join(", ")}`);
391
- }
392
- // What joins nothing is sorted among itself: a group of --min or more is a seed, the rest strays.
393
- const rest = left.length >= 2 ? cluster(spread, left) : left.map((i) => [i]);
394
- const seeds = [], strayRows = [];
395
- for (const g of rest.filter((g) => g.length >= min).sort((a, b) => b.length - a.length)) {
396
- const meanIn = (i) => g.filter((j) => j !== i).reduce((t, j) => t + D[i][j], 0) / (g.length - 1);
397
- const ordered = [...g].sort((a, b) => meanIn(a) - meanIn(b));
398
- const seed = { size: g.length, radius: r2(ordered.reduce((t, i) => t + meanIn(i), 0) / g.length), members: ordered.map((i) => refs[i].name) };
399
- seeds.push(seed);
400
- for (const i of ordered) {
401
- const { first } = read(i);
402
- lines.push(`${refs[i].name} → new family ${seeds.length} (${seed.size}, radius ${seed.radius}) nearest ${first.family} ${r2(first.distance)}`);
403
- }
404
- }
405
- for (const i of rest.filter((g) => g.length < min).flat()) {
406
- const { first, second, nearest } = read(i);
407
- strayRows.push({ name: refs[i].name, shot: refs[i].shot, nearest_family: first.family, distance: r2(first.distance), second, nearest });
408
- lines.push(`${refs[i].name} → stray nearest ${first.family} ${r2(first.distance)} near ${nearest.map((x) => x.name).join(", ")}`);
409
- }
410
- const outPath = outArg ? resolve(outArg) : join(dirname(resolve(input)), "assign.json");
411
- if (outPath === resolve(assignArg)) fail(`--out ${outArg} is the families file: write the assignment elsewhere`);
412
- mkdirSync(dirname(outPath), { recursive: true });
413
- writeFileSync(outPath, `${JSON.stringify({ spread, families: fams.map((f) => ({ id: f.id, size: f.members.length })), assigned, seeds, strays: strayRows }, null, 2)}\n`);
414
- console.log(`${fresh.length} new of ${n} references: ${assigned.length} join a family, ${seeds.length} new families proposed (${seeds.reduce((t, s) => t + s.size, 0)} references), ${strayRows.length} strays, spread ${spread}`);
415
- if (missing.length) console.log(`members of ${assignArg} not in ${input}, passed over: ${missing.join(", ")}`);
416
- for (const l of lines) console.log(l);
417
- console.log(`assign: ${relative(process.cwd(), outPath) || outPath}`);
418
- process.exit(0);
419
- }
420
-
421
- const groups = cluster(spread);
422
- // A bin: one family of 20 or more holding far more than its share: over three times the median of
423
- // the other families, or over two fifths of the pool. On a
424
- // pool of pictures only, one spread can make a few huge bins beside many strays, and lowering it
425
- // for the whole pool only adds strays. So a bin alone is sorted again at a lower spread, step by
426
- // step, until it splits into two or more families with most of it still in one; it is said.
427
- const splits = [];
428
- const isBin = (g, all) => {
429
- if (g.length < 20) return false;
430
- const others = all.filter((x) => x !== g && x.length >= min).map((x) => x.length).sort((a, b) => a - b);
431
- const med = others.length ? others[others.length >> 1] : 0;
432
- return g.length > 0.4 * n || (others.length >= 2 && g.length > 3 * med);
433
- };
434
- for (let pass = 0; pass < 6; pass++) {
435
- const bin = groups.find((g) => !g.tried && isBin(g, groups));
436
- if (!bin) break;
437
- bin.tried = true;
438
- for (let cut = spread - 0.02; cut >= Math.max(0.16, spread / 2) - 1e-9; cut -= 0.02) {
439
- const sub = cluster(cut, bin);
440
- const fams = sub.filter((g) => g.length >= min);
441
- const loose = sub.filter((g) => g.length < min).flat().length;
442
- if (fams.length >= 2 && Math.max(...fams.map((g) => g.length)) < 0.75 * bin.length && loose <= 0.3 * bin.length) {
443
- groups.splice(groups.indexOf(bin), 1, ...sub);
444
- splits.push(`a bin of ${bin.length} at ${Math.round(cut * 100) / 100} into ${fams.length} families${loose ? ` and ${loose} strays` : ""}`);
445
- break;
446
- }
447
- }
448
- }
449
- const done = groups.filter((g) => g.length >= min).sort((a, b) => b.length - a.length);
450
- const strayGroups = groups.filter((g) => g.length < min);
451
- const strays = strayGroups.flat();
452
- const pairs = strayGroups.filter((g) => g.length === 2);
453
- // How sensitive the cut is: what a little lower and higher would give.
454
- // With the largest family's size, so a count that holds steady while one bin swallows the pool shows.
455
- const countAt = (cut) => {
456
- const fams = cluster(cut).filter((g) => g.length >= min);
457
- return `${fams.length}${fams.length ? `, largest ${Math.max(...fams.map((g) => g.length))}` : ""}`;
458
- };
459
- const nearby = [Math.max(0.05, spread - 0.04), spread + 0.04].map((cut) => `${Math.round(cut * 100) / 100} → ${countAt(cut)}`);
460
-
461
- // ------------------------------------------------------------------ describe each family
462
- const meanTo = (i, group) => group.filter((j) => j !== i).reduce((t, j) => t + D[i][j], 0) / Math.max(1, group.length - 1);
463
- const range = (values, fmt) => {
464
- const s = values.filter((v) => v !== null && !Number.isNaN(v)).sort((a, b) => a - b);
465
- if (!s.length) return "";
466
- const lo = s.length >= 10 ? s[Math.floor(s.length * 0.1)] : s[0];
467
- const hi = s.length >= 10 ? s[Math.ceil(s.length * 0.9) - 1] : s.at(-1);
468
- return fmt(lo) === fmt(hi) ? `${fmt(lo)}` : `${fmt(lo)}–${fmt(hi)}`;
469
- };
470
- const tone = (l) => (l > 0.6 ? "light" : l < 0.12 ? "dark" : "mid");
471
- const describe = (group) => {
472
- const rs = group.map((i) => refs[i]);
473
- const tags = {};
474
- for (const field of ["picture", "layout", "scale", "type", "colour", "surface"]) {
475
- const counts = new Map();
476
- for (const r of rs) for (const w of (r.tags?.[field] || []).slice(0, 1)) counts.set(w, (counts.get(w) || 0) + 1);
477
- const [top] = [...counts].sort((x, y) => y[1] - x[1]);
478
- if (top) tags[field] = `${top[0]}${top[1] < rs.length ? ` ${top[1]}/${rs.length}` : ""}`;
479
- }
480
- const sized = rs.filter((r) => r.page && parseFloat(r.page.display) > 0);
481
- return {
482
- tags,
483
- tone: [...new Set(rs.map((r) => tone(num(r.image.lum) ?? 0.5)))].join(" and "),
484
- empty: `${range(rs.map((r) => num(r.image.empty)), Math.round)}%`,
485
- loud: `${range(rs.map((r) => num(r.image.loud)), Math.round)}%`,
486
- busy: range(rs.map((r) => num(r.image.busy)), Math.round),
487
- ...(sized.length ? { type: `${range(sized.map((r) => parseFloat(r.page.display)), Math.round)}px` } : {}),
488
- ...(rs.some((r) => r.page?.align) ? { align: [...new Set(rs.map((r) => r.page?.align).filter(Boolean))].join(" and ") } : {}),
489
- };
490
- };
491
- // The kinds of trait a family spreads widest on: where the eye should look first.
492
- const wideOn = (group) =>
493
- kinds
494
- .map(([name, k], ki) => {
495
- const vals = group.map((i) => refs[i].v[ki]).filter((v) => v !== null);
496
- let total = 0, count = 0;
497
- for (let a = 0; a < vals.length; a++) for (let b = a + 1; b < vals.length; b++) (total += k.dist(vals[a], vals[b])), count++;
498
- return [name, count ? total / count : 0];
499
- })
500
- .filter(([, d]) => d > 0.45)
501
- .map(([name]) => name);
502
-
503
- // Where a family sits on each slider they answered (its members' median), and how far that is from
504
- // what they asked: off by 1.5 or more on a slider is said, as a hint.
505
- const median = (xs) => {
506
- const v = xs.filter((x) => x !== null).sort((a, b) => a - b);
507
- return v.length ? (v[(v.length - 1) >> 1] + v[v.length >> 1]) / 2 : null;
508
- };
509
- function sliderFit(group) {
510
- if (!Object.keys(asked).length) return {};
511
- const at = {}, off = [];
512
- for (const key of Object.keys(asked)) {
513
- const m = median(group.map((i) => placeOf(refs[i])[key]));
514
- if (m === null) continue;
515
- at[key] = Math.round(m * 10) / 10;
516
- if (Math.abs(m - asked[key]) >= 1.5) off.push(`${SLIDERS[key][m > asked[key] ? 1 : 0]} (${at[key]}, asked ${asked[key]})`);
517
- }
518
- return { sliders: at, fit: off.length ? `off on ${off.join(", ")}` : Object.keys(at).length ? "near what they asked" : "" };
519
- }
520
-
521
- const families = done.map((group, f) => {
522
- const ordered = [...group].sort((a, b) => meanTo(a, group) - meanTo(b, group));
523
- const radius = ordered.reduce((t, i) => t + meanTo(i, group), 0) / ordered.length;
524
- const alsoOf = Object.fromEntries(ordered.filter((i) => also.has(refs[i].name)).map((i) => [refs[i].shot, also.get(refs[i].name)]));
525
- return { id: `f${f + 1}`, size: group.length, small: group.length < 6, radius: Math.round(radius * 100) / 100, wide: wideOn(group), ranges: describe(group), ...sliderFit(group), members: ordered.map((i) => refs[i].shot), ...(Object.keys(alsoOf).length ? { also: alsoOf } : {}) };
526
- });
527
- if (strays.length) {
528
- const nearest = Object.fromEntries(
529
- strays.map((i) => {
530
- const best = done.map((g, f) => [f, g.reduce((t, j) => t + D[i][j], 0) / g.length]).sort((a, b) => a[1] - b[1])[0];
531
- return [refs[i].shot, best ? `f${best[0] + 1}` : null];
532
- }),
533
- );
534
- families.push({ id: "strays", size: strays.length, small: true, stray: true, wide: [], ranges: { tags: {}, tone: [...new Set(strays.map((i) => tone(num(refs[i].image.lum) ?? 0.5)))].join(" and ") }, pairs: pairs.map((g) => g.map((i) => refs[i].shot)), nearest, members: strays.map((i) => refs[i].shot) });
535
- }
536
-
537
- const outPath = outArg ? resolve(outArg) : onlyLabel ? join(dirname(resolve(input)), "families", `${onlyLabel}-split`, "families.json") : join(dirname(resolve(input)), "families.json");
538
- mkdirSync(dirname(outPath), { recursive: true });
539
- writeFileSync(outPath, `${JSON.stringify({ spread, kinds: kinds.map(([name, k]) => ({ name, weight: k.weight })), families }, null, 2)}\n`);
540
- const sheetsDir = onlyLabel ? dirname(outPath) : join(dirname(outPath), "families");
541
- mkdirSync(sheetsDir, { recursive: true });
542
- // The first column is the reference's name (a motion reference's folder, not its frame), so --only finds it.
543
- const nameOfRef = new Map(refs.map((r) => [r.shot, r.name]));
544
- const refName = (shot) => nameOfRef.get(shot) ?? nameOfShot(shot);
545
- for (const f of families) writeFileSync(join(sheetsDir, `${f.id}.tsv`), `${f.members.map((s) => `${refName(s)}\t${resolve(s)}`).join("\n")}\n`);
546
-
547
- // ------------------------------------------------------------------ say it
548
- const tagLine = (f) => (Object.keys(f.ranges.tags || {}).length ? `${Object.values(f.ranges.tags).join(" · ")} | ` : "");
549
- const line = (f) => (f.stray ? "far from every family: place each by eye" : `${tagLine(f)}${f.ranges.tone} · empty ${f.ranges.empty} · loud ${f.ranges.loud} · busy ${f.ranges.busy}${f.ranges.type ? ` · type ${f.ranges.type}` : ""}${f.ranges.align ? ` · ${f.ranges.align}` : ""}`);
550
- const real = families.filter((f) => !f.stray);
551
- console.log(`${n} references${folded ? ` (${folded} more shots of the same sites folded in)` : ""}, ${real.length} families (${real.filter((f) => f.small).length} small), ${strays.length} strays, spread ${spread} (${nearby.join(", ")})`);
552
- console.log(`compared on: ${kinds.map(([name]) => name).join(", ")}`);
553
- if (splits.length) console.log(`split on their own, too big for one look: ${splits.join("; ")}. Check each on its sheet: the eye still merges what is one look`);
554
- const bins = done.filter((g) => isBin(g, done));
555
- if (bins.length) console.log(`still far bigger than the other families, likely a bin: ${bins.map((g) => g.length).join(", ")}. Split it by eye, or sort it alone with --only families/<id>.tsv --spread <lower>`);
556
- if (Object.keys(asked).length) {
557
- console.log(`sliders asked: ${Object.entries(asked).map(([k, v]) => `${SLIDERS[k][0]}–${SLIDERS[k][1]} ${v}`).join(", ")} (a hint for each family, never a cut)`);
558
- // The pool is what they chose or liked: where it sits against what they said.
559
- const pool = sliderFit(refs.map((_, i) => i));
560
- console.log(`what they chose sits at: ${Object.entries(pool.sliders).map(([k, v]) => `${k} ${v}`).join(", ")}${pool.fit.startsWith("off") ? `; ${pool.fit.replace("off on", "away from what they said on")}: ask which should lead` : "; close to what they said"}`);
561
- }
562
- const untagged = refs.filter((r) => !r.tags);
563
- if (untagged.length && untagged.length < n) console.log(`untagged, compared on their numbers only, and able to join groups the tags would keep apart: ${untagged.map((r) => r.name).join(", ")}. Tag them (tag.mjs) and sort again`);
564
- const blank = refs.filter((r) => num(r.image.empty) >= 99 && num(r.image.busy) < 0.5);
565
- if (blank.length) console.log(`near blank, check each on its sheet: ${blank.map((r) => r.name).join(", ")}`);
566
- // A live page that is not the real site (an error, maintenance, a bot check) is left out: that
567
- // reference is sorted on its picture alone, and the picture may be the same wrong page.
568
- const flagged = refs.filter((r) => r.flag);
569
- if (flagged.length) console.log(`pages that may not be the real site, sorted on their picture only; check each on its sheet and drop it if the picture is that page too: ${flagged.map((r) => `${r.name} (${r.flag})`).join(", ")}`);
570
- const stray = families.find((f) => f.stray);
571
- if (stray?.pairs.length) console.log(`pairs, each a family seed: ${stray.pairs.map((p) => p.map(refName).join("+")).join(", ")}`);
572
- if (stray) console.log(`nearest family of each stray: ${stray.members.map((s) => `${refName(s)}→${stray.nearest[s] || "none"}`).join(", ")}`);
573
- for (const f of families) {
574
- const notes = [f.small ? "small" : "", f.wide.length ? `wide on ${f.wide.join(", ")}` : ""].filter(Boolean).join(", ");
575
- console.log(`${f.id} ${String(f.size).padStart(4)} ${line(f)}${notes ? ` [${notes}]` : ""}${f.fit ? ` {${f.fit}}` : ""} typical: ${f.members.slice(0, 6).map(refName).join(", ")}`);
576
- }
577
-
578
- // ------------------------------------------------------------------ the board skeleton
579
- if (boardArg) {
580
- const boardPath = resolve(boardArg);
581
- if (existsSync(boardPath)) fail(`${boardArg} exists: write the skeleton elsewhere or remove it first`);
582
- const byShot = new Map(refs.map((r) => [r.shot, r]));
583
- const measured = (r) => {
584
- const p = r.page || {};
585
- const page = [parseFloat(p.display) > 0 && `type ${Math.round(parseFloat(p.display))}px`, p.align, num(p.gradient) > 0 && `gradient ${Math.round(num(p.gradient))}%`, p.scale && `scale ${p.scale}`, has(p.pictures) && `pictures ${p.pictures}%`].filter(Boolean);
586
- const tags = r.tags ? [Object.values(r.tags).map((w) => w.join("+")).filter((w) => w !== "none").join(" · ")] : [];
587
- return [...tags, tone(num(r.image.lum) ?? 0.5), `empty ${Math.round(num(r.image.empty))}%`, `loud ${Math.round(num(r.image.loud))}%`, `busy ${Math.round(num(r.image.busy))}`, ...page].join(" · ");
588
- };
589
- // Each pair of strays is its own group on the board, so it can be taken as the seed of a family.
590
- const pairOf = new Map();
591
- for (const [i, pair] of (stray?.pairs || []).entries()) for (const s of pair) pairOf.set(s, `Pair ${i + 1}`);
592
- const ordered = families.flatMap((f) => (f.stray ? [...f.members].sort((a, b) => (pairOf.has(a) ? 0 : 1) - (pairOf.has(b) ? 0 : 1) || String(pairOf.get(a)).localeCompare(String(pairOf.get(b)), undefined, { numeric: true })).map((s) => [f, s]) : f.members.map((s) => [f, s])));
593
- const cards = ordered.map(([f, s]) => {
594
- const r = byShot.get(s);
595
- // A URL shot stays a URL; a file is written relative to where the board is made.
596
- const shot = /^https?:\/\//i.test(s) ? s : relative(process.cwd(), resolve(s)).split("\\").join("/");
597
- const more = also.get(r.name);
598
- return `### ${r.name}
599
- - link: ${r.link || "none (shared in chat)"}
600
- - topic: ${pairOf.get(s) || f.id}
601
- - shot: ${shot}
602
- - measured: ${measured(r)}
603
- ${more ? `- also: ${more.join(", ")}\n` : ""}`;
604
- });
605
- writeFileSync(boardPath, `Families: ${families.map((f) => `${f.id} (${line(f)}) — ${f.size}`).join("; ")}\n\n${cards.join("\n")}`);
606
- console.log(`board: ${boardArg}, ${cards.length} cards`);
607
- }