Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit dcab2b796b9ea7eb555b6e9fa18b699a1fd07eb1
parent dec43f5fc1de067dba397e3058b15c7813b8e050
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu,  5 Nov 2026 23:08:03 -0500

measure: the build writes doc.measure, the slice the instruments draw from

measure-slice.mjs (pure) is the one object the dial, odometer, trail, goals,
peak, promise and diet modules read: for a deck cut whose manifest has a
measure ledger and render.chrome.deck.measure set, deckSchedule writes
`doc.measure` and scheduleSlices hands it on as `slices.measure`.

- events: every in-scope row the cut shows (the row's entryId or the entry's
  ledger pin), in cut order, at the cut second it lands -- the first word of
  the spoken figure (or the regime's word) in the clip's words when it has
  them, else the entry's quoteStart, else the segment's start; `tFrom` says
  which. hidden: the rows in scope no entry shows. Rows outside the scopes
  are ignored entirely.
- state: the state after each event, from the shown rows only -- current
  (last stated), remembered, goal (a goal_loss resolved against the start
  of the run open when he set it, else the last stated weight), goals, lost
  (the odometer), net, diet (offCloses: an off closes only the regime it
  names), promises.
- totals over the whole record in scope: lost, lostRuns, net, runs, goals,
  goalRepeats, diets (the walk's switch counter), peakDrift, under300,
  promises, span.
- The odometer rule (ruled 5 Nov, "go by his words"), lossRuns: real-time
  loss claims only (a delta below zero, no asOf, not `retro`); a run's
  figure is its highest claim; a row's explicit `run` places it, else a gap
  over bandGapDays starts a new run; the total is the sum.

measure-words.mjs reads each such clip's words (timed words, else its cues
spread by characters, labelled "cues"); the build passes them with each
segment's cut-record start. render.chrome.deck.measure = { scopes, scale,
asOf } is checked by modules/settings.mjs (a SETTINGS entry, `measure`) and
against the ledger's tracks by the build. A variant of a measure manifest
keeps its whole ledger as `measureLedger` (the hidden rows and the totals);
nothing changes for any other manifest or cut.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/report-to-video/build-video.mjs | 39+++++++++++++++++++++++++++++++++++++--
Mumtool/report-to-video/deck.mjs | 26++++++++++++++++++++++++--
Aumtool/report-to-video/measure-slice.mjs | 577+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/measure-slice.test.mjs | 229+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/measure-words.mjs | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/modules/index.mjs | 3+++
Mumtool/report-to-video/modules/rail.test.mjs | 2+-
Mumtool/report-to-video/modules/settings.mjs | 4++++
Mumtool/report-to-video/panel-model.mjs | 6++++--
9 files changed, 946 insertions(+), 7 deletions(-)

diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -165,6 +165,8 @@ import { // The effects region (`render.chrome.fx`, release 35): pure, in fx.mjs. import { fxOn, fxQuoteSpan, fxShiftConflicts, resolveFx, fxWhipJoins, fxWipeJoins, fxWordsOf, fxZoomJoins, validateFxEntries } from "./fx.mjs"; import { marksOf, stampsDrawn, validateClaims } from "./factcheck.mjs"; +import { measureOn, measureSettingsProblems, pinnedRows } from "./measure-slice.mjs"; +import { measureClipWords } from "./measure-words.mjs"; import { AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow, validateClipAudioEntries } from "./clip-audio.mjs"; import { blurCaptionLayout, blurPictureFilters, blurProblems, blurRecordOf, blurSpan, clipBlurOf, fittedSize, validateClipBlurEntries } from "./clip-blur.mjs"; import { validateFinaleEntries } from "./finale.mjs"; @@ -384,7 +386,11 @@ export function selectVariant(manifest, variant = DEFAULT_VARIANT) { // without the key, the same object again. // A look preset (`preset`, presets.mjs) is the base layer under it all: // laid first, so the brand and the intro read the render as it will be. - return introManifest(brandManifest(presetManifest({ ...manifest, variant, timeline, ledger, ...(posts !== undefined ? { posts } : {}) }))); + // A MEASURE ledger keeps its whole record beside the cut's rows: the + // instruments' totals and the finale's hidden rows are the rows no clip is + // behind (measure-slice.mjs). A headcount manifest gains nothing. + const measureLedger = manifest.ledgerSchema?.kind === "measure" ? { measureLedger: manifest.ledger ?? [] } : {}; + return introManifest(brandManifest(presetManifest({ ...manifest, variant, timeline, ledger, ...measureLedger, ...(posts !== undefined ? { posts } : {}) }))); } /** @@ -6087,6 +6093,10 @@ export async function measureChromeSchedule({ manifest, entries, segments, D, du clipGaps ??= new Map(); clipGaps.set(entries[i].id, recordGaps(rec)); } + // The measure slice (measure-slice.mjs): read only for a cut that writes + // one -- each clip's words for the second its figure is said, and the + // source second its segment starts at. + const measure = measureOn(manifest) ? await measureInputs({ manifest, entries, segments, render, provenance }) : null; // The variant's posts, placed on the clips this cut plays with their real // upload dates. A manifest without posts writes the schedule it always did. return deckSchedule({ @@ -6096,10 +6106,35 @@ export async function measureChromeSchedule({ manifest, entries, segments, D, du ...(clipClock ? { clipClock } : {}), ...(clipGaps ? { clipGaps } : {}), ...(estimated ? { estimated: true } : {}), + ...(measure ? { measure } : {}), }); } /** + * What deckSchedule needs for a measure slice that a manifest alone cannot + * give: the whole ledger, the words of each clip that shows a measure row + * (measure-words.mjs: the project's channels tree, then the corpus, then the + * build's cue reader), and the source second each one's segment starts at + * (its cut record's). + */ +async function measureInputs({ manifest, entries, segments, render, provenance }) { + const ledger = manifest.measureLedger ?? manifest.ledger ?? []; + const pins = pinnedRows(entries, ledger); + const ids = new Set(pins.keys()); + const words = await measureClipWords({ + entries, ids, provenance, channelsDirs: [FX_CHANNELS_DIR, DEFAULT_CHANNELS_DIR], cues: (e) => montageCues(e, provenance), + }); + const clock = new Map(); + for (let i = 0; i < entries.length; i += 1) { + if (!ids.has(entries[i].id) || !segments[i]) continue; + const rec = await readCutRecord(segments[i]).catch(() => null); + if (Number.isFinite(rec?.start)) clock.set(entries[i].id, rec.start); + } + for (const [id, w] of words) EMIT("log", { message: `measure: ${id}'s figures timed by its ${w.from}` }); + return { ledgerSchema: manifest.ledgerSchema, ledger, words, clock, render }; +} + +/** * The chat for the clips that ask for it (`chat: true`, chat.mjs): each * clip's video's `live_chat.cues.json` (SOURCE seconds), and `clock` the * source second each clip's segment starts at (its cut record's, else the @@ -6525,7 +6560,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly ...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole), ...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole, { schedule: false }), ...validateTransitionStyle(whole), ...validateLook(whole), ...validateClipAudioEntries(whole), ...validateClipBlurEntries(whole), ...validateFinaleEntries(whole), - ...validateGapEntries(whole), + ...validateGapEntries(whole), ...measureSettingsProblems(whole), ]; if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`); } diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -18,6 +18,7 @@ import { createHash } from "node:crypto"; import { archiveMomentUrl } from "./site-links.mjs"; import { playEdges, soundEdges as soundEdgesOf, soundOnSegment } from "./mute.mjs"; import { gappedLength, offsetIn, recordGaps, renderGaps } from "./gaps.mjs"; +import { measureOn, measureSlice } from "./measure-slice.mjs"; import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs"; import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs"; @@ -175,7 +176,9 @@ export function validateChrome(chrome, render = {}) { // (counter.mjs: the tally's named series). // `rail` (rail.mjs: `{labels}`) likewise has no default to fill, nor // `sectionTitle` (section-title.mjs: the current section's name). - unknownKeys(d, [...Object.keys(DECK_DEFAULTS), "finale", "claims", "counter", "rail", "sectionTitle"], w, errors); + // `measure` (measure-slice.mjs: the measure ledger's slice for the + // instruments) likewise. + unknownKeys(d, [...Object.keys(DECK_DEFAULTS), "finale", "claims", "counter", "rail", "sectionTitle", "measure"], w, errors); deckChecked = true; } errors.push(...entry.validate(settingValue(chrome, entry), { render, chrome, deck: d, where: w })); @@ -1143,7 +1146,7 @@ export function deckQrUrl(entry, provenance = {}, { links = DECK_DEFAULTS.qr.lin */ export function deckSchedule({ entries, durs, D, render, provenance = {}, metas = [], estimated = false, posts = [], frameScan = null, - fxWords = null, fxClock = null, clipClock = null, clipGaps = null, chat = null, + fxWords = null, fxClock = null, clipClock = null, clipGaps = null, chat = null, measure = null, }) { const deck = resolveDeck(render); // A clip's gaps (gaps.mjs) on its segment: its cut record's as built @@ -1330,6 +1333,23 @@ export function deckSchedule({ doc.finale = { ...doc.finale, box, railBottom: room.railBottom, ...(room.textScale !== 1 ? { textScale: room.textScale } : {}) }; if (was && doc.moves) doc.moves = doc.moves.map((m) => (m.to === was ? { ...m, to: box } : m)); } + // The measure slice (measure-slice.mjs): a measure ledger's rows in the + // cut's clock and the instruments' state after each, for the dial, the + // odometer and the rest. Only with a measure ledger and + // `render.chrome.deck.measure`: a cut without them writes what it did. + // `measure` is `{ ledgerSchema, ledger, words?, clock?, asOf? }` -- the + // WHOLE ledger (a variant keeps only its pinned rows), each clip's words + // and the source second its segment starts at (the cut record's; else the + // play window's, here). + if (measure && measureOn({ ledgerSchema: measure.ledgerSchema, render })) { + const clock = new Map(entries.filter((e) => e.type === "clip").map((e) => [e.id, measure.clock?.get(e.id) ?? playWindow(e, render).from])); + const gaps = new Map(entries.filter((e) => e.type === "clip" && gapsFor(e).length).map((e) => [e.id, gapsFor(e)])); + doc.measure = measureSlice( + { ledgerSchema: measure.ledgerSchema, ledger: measure.ledger ?? [], render, timeline: entries }, + doc, + { words: measure.words ?? null, clock, gaps, asOf: measure.asOf ?? null }, + ); + } return doc; } @@ -1827,6 +1847,8 @@ export function estimateSchedule(manifest, { metas = [], noXfade = false } = {}) metas, estimated: true, frameScan: manifest.frameScan ?? null, + // A measure ledger's slice, timed by the quotes (no words in an estimate). + ...(manifest.ledgerSchema ? { measure: { ledgerSchema: manifest.ledgerSchema, ledger: manifest.measureLedger ?? manifest.ledger ?? [] } } : {}), }); } diff --git a/umtool/report-to-video/measure-slice.mjs b/umtool/report-to-video/measure-slice.mjs @@ -0,0 +1,577 @@ +// THE MEASURE SLICE (weight video rev 9): one object every measure module +// draws from -- the dial, the odometer, the trail, the goals, the peak, the +// promise clock, the diet badge. Written into a deck cut's schedule.json as +// `doc.measure` by the build when the manifest carries a measure ledger +// (`ledgerSchema.kind: "measure"`) and `render.chrome.deck.measure` is set; +// `scheduleSlices(doc).measure` hands it to each module's page whole. +// +// Pure: no I/O. The build reads each clip's words (measure-words.mjs) and the +// source second each segment starts at, and passes them in. +// +// events every ledger row in scope the CUT SHOWS -- pinned to an entry in +// the cut, by the row's `entryId` or the entry's ledger pin +// (`claim: "<row id>"`) -- in cut order, each at the cut second +// it lands: the spoken number's word time when the clip's words +// have it, else the entry's quoteStart, else the segment's start. +// hidden the rows in scope no entry of the cut shows (t: null). +// state one entry per event, the state AFTER it, sorted by t; state[0] +// (t: 0) is the state before any event. Built from the EVENTS +// only: a hidden row never moves a number on screen. +// totals over events + hidden: the whole record in scope. +// +// The odometer rule (ruled 5 Nov 2026, "go by his words"): see lossRuns. +import { chronological, dateKey, daysBetween } from "./ledger-shared.mjs"; +import { measureDisplay, measureQualifier, measureSchema, measureTotals, plotDate } from "./measure-totals.mjs"; +import { goalCell, nextRegime, offOf } from "./panel-model.mjs"; +import { offsetIn } from "./gaps.mjs"; + +export const MEASURE_SLICE_VERSION = 1; + +/** The populations a promise is written in: what he says he will do, and a later word about it. */ +export const PROMISE_FORMS = Object.freeze(["promise", "promise_check"]); + +/** `render.chrome.deck.measure`'s keys. */ +export const MEASURE_SETTINGS_KEYS = Object.freeze(["scopes", "scale", "asOf"]); + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const isIso = (v) => typeof v === "string" && /^\d{4}-\d{2}-\d{2}$/.test(v) && !Number.isNaN(Date.parse(`${v}T00:00:00Z`)); +const r1 = (v) => Math.round(v * 10) / 10; +const r3 = (v) => Math.round(v * 1000) / 1000; + +/** + * `render.chrome.deck.measure`, checked: `{ scopes?, scale?, asOf? }` -- + * `scopes` a list of track keys (unique, at least one), `scale` `{ min, max }` + * (numbers, min < max), `asOf` a date (YYYY-MM-DD). Whether the scopes are + * the ledger's tracks is measureSettingsProblems' (it has the schema). + * + * @returns {string[]} + */ +export function validateMeasureSettings(v, where = "render.chrome.deck.measure") { + if (v === undefined) return []; + if (!isObj(v)) return [`${where} must be { scopes, scale, asOf }`]; + const errors = []; + for (const k of Object.keys(v)) if (!MEASURE_SETTINGS_KEYS.includes(k)) errors.push(`${where}.${k} is not a measure setting (${MEASURE_SETTINGS_KEYS.join(", ")})`); + if (v.scopes !== undefined) { + if (!Array.isArray(v.scopes) || !v.scopes.length || v.scopes.some((s) => typeof s !== "string" || !s.trim())) { + errors.push(`${where}.scopes must be a list of the ledger's track keys (at least one)`); + } else if (new Set(v.scopes).size !== v.scopes.length) errors.push(`${where}.scopes names a track twice`); + } + if (v.scale !== undefined) { + const s = v.scale; + if (!isObj(s) || !Number.isFinite(s.min) || !Number.isFinite(s.max)) errors.push(`${where}.scale must be { min, max } in the ledger's unit`); + else if (s.min >= s.max) errors.push(`${where}.scale.min must be below scale.max`); + else for (const k of Object.keys(s)) if (k !== "min" && k !== "max") errors.push(`${where}.scale.${k} is not a scale setting (min, max)`); + } + if (v.asOf !== undefined && !isIso(v.asOf)) errors.push(`${where}.asOf must be a date (YYYY-MM-DD)`); + return errors; +} + +/** Does this manifest carry a measure ledger? */ +export const isMeasureManifest = (manifest) => isObj(manifest?.ledgerSchema) && manifest.ledgerSchema.kind === "measure"; + +/** Does this cut write a measure slice: a deck, a measure ledger, and `render.chrome.deck.measure` set? */ +export function measureOn(manifest) { + const chrome = manifest?.render?.chrome; + return isMeasureManifest(manifest) && isObj(chrome) && chrome.layout === "deck" && isObj(chrome.deck?.measure); +} + +/** + * The measure settings against the manifest: the deck's `measure` shape, that + * the manifest has a measure ledger for it, and that every scope is one of + * its tracks. + * + * @returns {string[]} + */ +export function measureSettingsProblems(manifest) { + const v = manifest?.render?.chrome?.deck?.measure; + if (v === undefined) return []; + const errors = validateMeasureSettings(v); + if (errors.length) return errors; + if (!isMeasureManifest(manifest)) return ['render.chrome.deck.measure needs a measure ledger (ledgerSchema.kind "measure")']; + const tracks = measureSchema(manifest.ledgerSchema).tracks.map((t) => t.key); + for (const s of v.scopes ?? []) if (!tracks.includes(s)) errors.push(`render.chrome.deck.measure.scopes: "${s}" is not a track of the ledger (${tracks.join(", ")})`); + return errors; +} + +/** + * The settings with their defaults: scopes every track, the scale the + * schema's yMin..yMax, asOf the render's date. + */ +export function resolveMeasure(manifest, { asOf = null } = {}) { + const schema = measureSchema(manifest.ledgerSchema); + const v = manifest?.render?.chrome?.deck?.measure ?? {}; + const today = new Date().toISOString().slice(0, 10); + return { + schema, + scopes: Array.isArray(v.scopes) && v.scopes.length ? [...v.scopes] : schema.tracks.map((t) => t.key), + scale: isObj(v.scale) ? { min: v.scale.min, max: v.scale.max } : { min: schema.yMin, max: schema.yMax }, + asOfRender: asOf ?? v.asOf ?? today, + }; +} + +// --------------------------------------------------------------------------- +// The odometer +// --------------------------------------------------------------------------- + +/** + * Is this row a REAL-TIME loss claim -- one the odometer counts? A `delta` + * on the (first) value track, below zero, about now: no `asOf`, and not + * marked `retro` (a loss he describes in the past -- "I also lost 64 pounds" + * -- with no date to put in `asOf`). + */ +export function isRealtimeLoss(row, schema) { + const s = measureSchema(schema); + const valueTrack = s.tracks.find((t) => t.role === "value")?.key ?? null; + return row?.scope === valueTrack && row.population === "delta" && Number(row.value) < 0 && + (row.asOf === undefined || row.asOf === null || row.asOf === "") && row.retro !== true; +} + +/** + * The runs of real-time loss claims, by HIS words (ruled 5 Nov 2026): + * + * - only real-time loss claims count (isRealtimeLoss); + * - a run is a sequence of them, and its contribution is the HIGHEST claim + * in it -- the figure he gave, whatever app or other figure he cites; + * - a row's explicit `run` (a whole number, written by the ledger writer + * where his words say which run a claim continues -- "since I started") + * places it; otherwise a gap of more than `bandGapDays` since the last + * claim starts a new run, and a shorter one continues it; + * - the total is the sum of the runs' peaks. + * + * Walked in the order he said them (date, then id). + * + * @returns {{ runs: Array<{ run: number, start: string, end: string, peak: number, row: string, rows: string[] }>, + * runOf: Map<string, number>, claims: Array<{ id: string, date: string, run: number }>, total: number }} + */ +export function lossRuns(rows, schema) { + const s = measureSchema(schema); + const claims = chronological((rows ?? []).filter((r) => isRealtimeLoss(r, s))); + const byRun = new Map(); + const runOf = new Map(); + let prev = null; + let next = 0; + for (const c of claims) { + let run; + if (Number.isInteger(c.run) && c.run >= 0) run = c.run; + else if (prev && Math.round(daysBetween(prev.date, c.date)) <= s.bandGapDays) run = runOf.get(prev.id); + else run = next; + next = Math.max(next, run + 1); + runOf.set(c.id, run); + const v = Math.abs(Number(c.value)); + const r = byRun.get(run); + if (!r) byRun.set(run, { run, start: c.date, end: c.date, peak: v, row: c.id, rows: [c.id] }); + else { + r.rows.push(c.id); + if (dateKey(c.date) > dateKey(r.end)) r.end = c.date; + if (dateKey(c.date) < dateKey(r.start)) r.start = c.date; + if (v > r.peak) { r.peak = v; r.row = c.id; } + } + prev = c; + } + const runs = [...byRun.values()].sort((a, b) => a.run - b.run); + return { runs, runOf, claims: claims.map((c) => ({ id: c.id, date: c.date, run: runOf.get(c.id) })), total: r1(runs.reduce((n, r) => n + r.peak, 0)) }; +} + +// --------------------------------------------------------------------------- +// A row as an event +// --------------------------------------------------------------------------- + +/** A row's kind on the instruments, from its form and its track. */ +export function kindOf(row, schema) { + const s = measureSchema(schema); + const role = s.tracks.find((t) => t.key === row?.scope)?.role ?? null; + switch (row?.population) { + case "current": return "stated"; + case "past": return "remembered"; + case "delta": return Number(row.value) < 0 ? "lost" : "gained"; + case "goal": return "goal"; + case "goal_loss": return "goalLoss"; + case "overweight_by": return "overBy"; + case "promise": return "promise"; + case "promise_check": return "promiseCheck"; + case "status": return role === "regime" ? "diet" : "status"; + default: return row?.population ?? null; + } +} + +/** A hidden row's source: an X post when its link or channel says so, else a clip. */ +const rowSource = (row) => (/(^|\/\/)(x|twitter)\.com\//.test(String(row?.citeUrl ?? "")) || /-x$/i.test(String(row?.channel ?? "")) ? "post" : "clip"); + +/** An entry's source kind: a clip, a post, or a card (anything else). */ +const entrySource = (entry) => (entry?.type === "clip" ? "clip" : entry?.type === "post" ? "post" : "card"); + +function eventOf(row, schema, runOf) { + const s = measureSchema(schema); + const kind = kindOf(row, s); + const role = s.tracks.find((t) => t.key === row.scope)?.role ?? null; + const n = Number(row.value); + return { + row: row.id, + scope: row.scope, + date: row.date ?? null, + asOf: row.asOf ?? null, + kind, + value: role === "regime" || !Number.isFinite(n) || row.value === null || row.value === "" ? null : n, + qualifier: measureQualifier(row, s), + display: measureDisplay(row, s), + label: row.label ?? null, + quote: row.quote ?? null, + deadline: row.deadline ?? null, + due: isIso(row.due) ? row.due : null, + regime: role === "regime" ? String(row.value) : null, + event: role === "regime" ? row.event ?? null : null, + run: kind === "lost" && runOf.has(row.id) ? runOf.get(row.id) : null, + }; +} + +// --------------------------------------------------------------------------- +// When a row lands: the spoken number in the clip's words +// --------------------------------------------------------------------------- + +const ONES = { zero: 0, oh: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18, nineteen: 19 }; +const TENS = { twenty: 20, thirty: 30, forty: 40, fourty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90 }; +const norm = (w) => String(w ?? "").toLowerCase().replace(/[“”"',!?;:()\[\]]/g, "").replace(/\.$/, "").replace(/^\$/, ""); + +/** + * The numbers said in a run of words: `{ i, value }` for each, `i` the index + * of its first word -- digits ("291.5", "60", "58.2lbs") and number words + * ("two hundred ninety one point five", "a hundred", "fifty eight point two"). + * + * @param {Array<{ text: string }>} words + */ +export function spokenNumbers(words) { + const toks = words.map((w) => norm(w.text)); + const out = []; + for (let i = 0; i < toks.length; i += 1) { + const t = toks[i]; + const digits = /^(\d+(?:\.\d+)?)(?:lbs?|pounds?)?$/.exec(t); + if (digits) { out.push({ i, value: Number(digits[1]) }); continue; } + const starts = t in ONES || t in TENS || (t === "a" && toks[i + 1] === "hundred"); + if (!starts) continue; + let total = 0; + let cur = 0; + let j = i; + let any = false; + for (; j < toks.length; j += 1) { + const w = toks[j]; + if (w in ONES) { cur += ONES[w]; any = true; } else if (w in TENS) { cur += TENS[w]; any = true; } else if (w === "a" && toks[j + 1] === "hundred") { cur += 1; } else if (w === "hundred") { cur = (cur || 1) * 100; any = true; } else if (w === "thousand") { total += (cur || 1) * 1000; cur = 0; any = true; } else if (w === "and" && any && (toks[j + 1] in ONES || toks[j + 1] in TENS)) { /* "a hundred and ten" */ } else break; + } + let value = total + cur; + // "point five", "point one five": the digits after the point, one word each. + if (toks[j] === "point" && toks[j + 1] in ONES && ONES[toks[j + 1]] < 10) { + let frac = ""; + let k = j + 1; + while (k < toks.length && toks[k] in ONES && ONES[toks[k]] < 10) { frac += String(ONES[toks[k]]); k += 1; } + value = Number(`${value}.${frac}`); + j = k; + } + if (any) out.push({ i, value }); + i = j - 1; + } + return out; +} + +/** The words that name a regime when he says it, beyond its key and label. */ +const REGIME_WORDS = { glp1: ["ozempic", "ozimpic", "wegovy", "mounjaro", "glp", "glp-1", "semaglutide", "jab"], fasting: ["fasting", "fast"], calories: ["calories", "calorie"], carnivore: ["carnivore"], keto: ["keto", "ketogenic"] }; + +/** The figure the row's quote says, as he would say it: the magnitude, for a loss or a loss goal. */ +function spokenTargets(row, kind) { + if (!["stated", "remembered", "lost", "gained", "goal", "goalLoss", "overBy"].includes(kind)) return null; + const out = []; + const n = Number(row.value); + if (Number.isFinite(n)) out.push(Math.abs(n)); + // A range he gave ("220-240", "330-340 lb"): either end is his figure. + const range = /(\d+(?:\.\d+)?)\s*[-–]\s*(\d+(?:\.\d+)?)/.exec(String(row.display ?? "")); + if (range) out.push(Number(range[1]), Number(range[2])); + return out.length ? out : null; +} + +/** + * The source second the row's figure is said in `words` (`[{ text, start }]`, + * source seconds), searched from `anchor` (a second before it) to the end, + * then anywhere: the first word of the spoken number (a figure row), or the + * regime's word (a diet row). Null when the words never say it. + */ +export function spokenAt(row, kind, words, anchor = -Infinity, schema = null) { + if (!Array.isArray(words) || !words.length) return null; + const pick = (hits) => hits.find((h) => words[h].start >= anchor - 1) ?? hits[0] ?? null; + const targets = spokenTargets(row, kind); + if (targets !== null) { + const nums = spokenNumbers(words); + const exact = nums.filter((n) => targets.some((v) => Math.abs(n.value - v) < 0.05)).map((n) => n.i); + const i = pick(exact); + return i === null ? null : words[i].start; + } + if (kind === "diet") { + const key = String(row.value ?? ""); + const label = schema ? measureSchema(schema).regimes.find((r) => r.key === key)?.label ?? "" : ""; + const names = new Set([key, ...(REGIME_WORDS[key] ?? []), ...label.toLowerCase().split(/[^a-z0-9-]+/).filter((w) => w.length > 3)]); + const hits = words.map((w, i) => (names.has(norm(w.text)) ? i : -1)).filter((i) => i >= 0); + const i = pick(hits); + return i === null ? null : words[i].start; + } + return null; +} + +// --------------------------------------------------------------------------- +// The slice +// --------------------------------------------------------------------------- + +/** + * The rows of the cut's entries: entry id → the in-scope row ids it shows, in + * ledger order -- each row's `entryId`, and each entry's ledger pin + * (`claim: "<row id>"`). + */ +export function pinnedRows(timeline, rows) { + const ids = new Set(rows.map((r) => r.id)); + const out = new Map(); + const add = (entryId, rowId) => { + if (!ids.has(rowId)) return; + const list = out.get(entryId) ?? []; + if (!list.includes(rowId)) list.push(rowId); + out.set(entryId, list); + }; + const inCut = new Set((timeline ?? []).map((e) => e?.id)); + for (const r of rows) if (r.entryId && inCut.has(r.entryId)) add(r.entryId, r.id); + for (const e of timeline ?? []) if (typeof e?.claim === "string" && e.claim.trim()) add(e.id, e.claim.trim()); + const order = new Map(rows.map((r, i) => [r.id, i])); + for (const list of out.values()) list.sort((a, b) => order.get(a) - order.get(b)); + return out; +} + +/** + * The measure slice of a cut. + * + * @param {object} manifest the variant's manifest: `ledgerSchema`, `render`, + * `timeline` (the cut's entries), and `ledger` -- the WHOLE ledger, or pass + * it as `opts.ledger` (a variant's manifest keeps only the pinned rows). + * @param {{ segments: Array<{ id: string, start: number, duration: number }> }} schedule + * the deck schedule (deck.mjs deckSchedule's document, or one like it). + * @param {{ ledger?: object[], asOf?: string|null, + * words?: Map<string, { words: Array<{ text: string, start: number }>, from?: string }>, + * clock?: Map<string, number>, gaps?: Map<string, Array<{ from: number, to: number }>> }} [opts] + * `words` each clip's words in SOURCE seconds; `clock` the source second + * each clip's segment starts at (its cut record's, else the play window's); + * `gaps` a clip's gaps. A clip with none of them lands on its quoteStart, + * against its own start. + */ +export function measureSlice(manifest, schedule, opts = {}) { + const settings = resolveMeasure(manifest, { asOf: opts.asOf ?? null }); + const s = settings.schema; + const problems = measureSettingsProblems(manifest); + if (problems.length) throw new Error(problems.join("; ")); + const scopes = new Set(settings.scopes); + const ledger = (opts.ledger ?? manifest.ledger ?? []).filter((r) => isObj(r) && typeof r.id === "string"); + const rows = ledger.filter((r) => scopes.has(r.scope)); + const byId = new Map(rows.map((r) => [r.id, r])); + const { runs, runOf, claims: lossClaims, total } = lossRuns(rows, s); + const runById = new Map(runs.map((r) => [r.run, r])); + + // ---- events: each pinned row at the cut second it lands ------------------- + const timeline = manifest.timeline ?? []; + const entryById = new Map(timeline.map((e) => [e.id, e])); + const segs = (schedule?.segments ?? []).filter((g) => entryById.has(g.id)); + const segIndex = new Map(segs.map((g, i) => [g.id, i])); + const pins = pinnedRows(timeline.filter((e) => segIndex.has(e.id)), rows); + const shown = new Set(); + const events = []; + for (const seg of segs) { + const entry = entryById.get(seg.id); + const ids = pins.get(seg.id) ?? []; + const from = opts.clock?.get(seg.id) ?? entry.cutStart ?? entry.start ?? null; + const gaps = opts.gaps?.get(seg.id) ?? null; + const words = opts.words?.get(seg.id) ?? null; + const toCut = (src) => { + if (!Number.isFinite(src) || !Number.isFinite(from)) return null; + const off = offsetIn(src, from, gaps); + return r3(Math.min(seg.start + seg.duration, Math.max(seg.start, seg.start + off))); + }; + for (const id of ids) { + if (shown.has(id)) continue; + const row = byId.get(id); + const ev = eventOf(row, s, runOf); + // His figure's own second when the words have it; searched from the + // row's cite when that is inside the clip (an entry showing two rows + // says them at two seconds), else from the quote's start. + const inWindow = (v) => Number.isFinite(v) && Number.isFinite(entry.start) && Number.isFinite(entry.end) && v >= entry.start && v <= entry.end; + const anchor = ids.length > 1 && inWindow(row.cite) ? row.cite : entry.quoteStart ?? entry.start ?? -Infinity; + const said = entry.type === "clip" && words ? spokenAt(row, ev.kind, words.words, anchor, s) : null; + let t = said !== null ? toCut(said) : null; + let tFrom = t !== null ? (words.from === "cues" ? "cues" : "words") : null; + if (t === null && entry.type === "clip") { + const q = ids.length > 1 && inWindow(row.cite) ? row.cite : entry.quoteStart; + t = toCut(q); + if (t !== null) tFrom = "quote"; + } + if (t === null) { t = r3(seg.start); tFrom = "segment"; } + events.push({ t, tFrom, segment: seg.id, ...ev, source: entrySource(entry), _seg: segIndex.get(seg.id) }); + shown.add(id); + } + } + events.sort((a, b) => a.t - b.t || a._seg - b._seg || dateKey(a.date).localeCompare(dateKey(b.date)) || String(a.row).localeCompare(String(b.row))); + for (const e of events) delete e._seg; + const hidden = chronological(rows.filter((r) => !shown.has(r.id))) + .map((r) => ({ t: null, tFrom: null, segment: null, ...eventOf(r, s, runOf), source: rowSource(r) })); + + // ---- the record's own figures, for the state's fixed ends ----------------- + const valueTrack = s.tracks.find((t) => t.role === "value")?.key ?? null; + const regimeTrack = s.tracks.find((t) => t.role === "regime" && scopes.has(t.key))?.key ?? null; + const readings = chronological(rows.filter((r) => r.scope === valueTrack && (r.population === "current" || r.population === "past") && Number.isFinite(Number(r.value)))); + const firstReading = [...readings].sort((a, b) => dateKey(plotDate(a)).localeCompare(dateKey(plotDate(b))) || String(a.id).localeCompare(String(b.id)))[0] ?? null; + const netFrom = firstReading ? { value: Number(firstReading.value), date: plotDate(firstReading), row: firstReading.id } : null; + + /** + * A loss goal's target weight: against the start of the run open when he + * set it, when the record knows that start -- a remembered weight about a + * day within bandGapDays before the run's first claim, said by the goal's + * date (the latest said wins) -- else against the last weight he stated by + * then, else none (his words stay the goal). The run open when he set it: + * the run of his last loss claim before it, within bandGapDays, else of his + * next one within bandGapDays (a goal set as a run begins). + */ + const runAt = (d) => { + const before = lossClaims.filter((c) => dateKey(c.date) <= dateKey(d)).pop(); + if (before && Math.round(daysBetween(before.date, d)) <= s.bandGapDays) return runById.get(before.run) ?? null; + const after = lossClaims.find((c) => dateKey(c.date) > dateKey(d)); + if (after && Math.round(daysBetween(d, after.date)) <= s.bandGapDays) return runById.get(after.run) ?? null; + return null; + }; + const goalBase = (row) => { + const d = row.date; + const run = runAt(d); + if (run) { + const starts = readings.filter((r) => r.population === "past" && r.asOf && dateKey(r.date) <= dateKey(d) && + dateKey(r.asOf) <= dateKey(run.start) && Math.round(daysBetween(r.asOf, run.start)) <= s.bandGapDays); + const last = starts[starts.length - 1]; + if (last) return { value: Number(last.value), row: last.id, from: "runStart" }; + } + const stated = readings.filter((r) => r.population === "current" && dateKey(r.date) <= dateKey(d)); + const last = stated[stated.length - 1]; + return last ? { value: Number(last.value), row: last.id, from: "stated" } : null; + }; + const goalOf = (row) => { + const base = row.population === "goal_loss" ? goalBase(row) : null; + const cell = goalCell(row, base, s); + return { value: cell.value, loss: cell.loss, deadline: cell.deadline, due: isIso(row.due) ? row.due : null, row: row.id, display: cell.display, base }; + }; + + // ---- the state after each event ------------------------------------------- + let current = null; + const remembered = []; + let goal = null; + const goals = []; + const peaks = new Map(); + let regime = null; + let dietN = 0; + const promises = new Map(); + const snapshot = (t) => { + const lostRuns = [...peaks.entries()].sort((a, b) => a[0] - b[0]).map(([run, p]) => ({ run, start: runById.get(run)?.start ?? null, peak: p.peak, row: p.row })); + const off = regimeTrack ? offOf(s, regimeTrack)?.key ?? null : null; + return { + t, + current: current ? { ...current } : null, + remembered: remembered.map((x) => ({ ...x })), + goal: goal ? { ...goal, ...(goal.base ? { base: { ...goal.base } } : {}) } : null, + goals: [...goals], + lost: { total: r1(lostRuns.reduce((n, r) => n + r.peak, 0)), runs: lostRuns }, + net: { + from: netFrom ? { ...netFrom } : null, + to: current ? { value: current.value, date: current.asOf ?? current.date, row: current.row } : null, + value: netFrom && current ? r1(current.value - netFrom.value) : null, + }, + diet: regime && regime.key !== off ? { regime: regime.key, display: regime.display, row: regime.row, n: dietN, since: regime.since } : null, + promises: [...promises.values()].map((p) => ({ ...p, checks: [...p.checks] })), + }; + }; + const state = [snapshot(0)]; + for (const ev of events) { + const row = byId.get(ev.row); + if (ev.kind === "stated" && ev.value !== null) current = { value: ev.value, qualifier: ev.qualifier, row: ev.row, date: ev.date, asOf: ev.asOf }; + else if (ev.kind === "remembered" && ev.value !== null) remembered.push({ value: ev.value, asOf: ev.asOf, row: ev.row, date: ev.date }); + else if (ev.kind === "goal" || ev.kind === "goalLoss") { goal = goalOf(row); goals.push(ev.row); } + else if (ev.kind === "lost" && ev.run !== null) { + const v = Math.abs(ev.value); + const p = peaks.get(ev.run); + if (!p || v > p.peak) peaks.set(ev.run, { peak: v, row: ev.row }); + } else if (ev.kind === "diet" && row.scope === regimeTrack) { + const was = regime; + regime = nextRegime(regime, row, s); + const off = offOf(s, regimeTrack)?.key ?? null; + if (regime && regime.key !== off && (!was || was.key !== regime.key)) dietN += 1; + } else if (ev.kind === "promise") { + promises.set(ev.row, { row: ev.row, said: ev.date, what: ev.display, due: ev.due, kept: row.kept === true, checks: [] }); + } else if (ev.kind === "promiseCheck") { + const p = promises.get(row.promise); + if (p) { p.checks.push(ev.row); if (row.kept === true) p.kept = true; } + } + state.push(snapshot(ev.t)); + } + // `asOf` is the state's own bookkeeping: the current reading carries the + // date the contract names, and NET its plot date. + for (const st of state) if (st.current) delete st.current.asOf; + + // ---- totals over the whole record in scope -------------------------------- + const all = chronological(rows); + const lastStated = [...readings].filter((r) => r.population === "current").pop() ?? null; + const goalRows = all.filter((r) => r.population === "goal" || r.population === "goal_loss"); + const repeats = {}; + for (const r of goalRows) { const d = measureDisplay(r, s); repeats[d] = (repeats[d] ?? 0) + 1; } + const goalRepeats = Object.fromEntries(Object.entries(repeats).filter(([, n]) => n > 1).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))); + // THE PEAK DRIFT: the weight he remembers starting from, retold. A + // remembered weight above every weight he ever stated at the time, about a + // day inside the stated record -- so the 2008 wedding is not a start, and + // neither is a floor or a ladder rung below what he was saying then. + const stated = readings.filter((r) => r.population === "current"); + const maxStated = stated.length ? Math.max(...stated.map((r) => Number(r.value))) : Infinity; + const firstStated = stated.length ? stated.map((r) => dateKey(r.date)).sort()[0] : null; + const peakDrift = [...new Set(readings.filter((r) => r.population === "past" && r.asOf && firstStated && dateKey(r.asOf) >= firstStated && Number(r.value) > maxStated).map((r) => Number(r.value)))].sort((a, b) => a - b); + // UNDER 300: a weight he stated below it, or "under 300" itself -- never a + // bound the other way ("over 240" is not a weight under 300). + const under = stated.filter((r) => { + const q = measureQualifier(r, s); + return q !== ">" && (Number(r.value) < 300 || (Number(r.value) === 300 && q === "<")); + }); + const dates = all.map((r) => plotDate(r)).filter(Boolean).map(dateKey).sort(); + const promiseRows = all.filter((r) => r.population === "promise"); + const checksOf = (id) => all.filter((r) => r.population === "promise_check" && r.promise === id); + let diets = 0; + try { + diets = measureTotals(rows, s, { strict: false }).switches; + } catch { + diets = 0; + } + const totals = { + lost: total, + lostRuns: runs.map(({ run, start, end, peak, row, rows: ids }) => ({ run, start, end, peak, row, rows: ids })), + net: { + from: netFrom?.value ?? null, + to: lastStated ? Number(lastStated.value) : null, + value: netFrom && lastStated ? r1(Number(lastStated.value) - netFrom.value) : null, + fromRow: netFrom?.row ?? null, + toRow: lastStated?.id ?? null, + }, + runs: runs.length, + goals: goalRows.length, + goalRepeats, + diets, + peakDrift, + under300: { said: under.length, rows: under.map((r) => r.id) }, + promises: promiseRows.map((p) => { + const checks = checksOf(p.id); + return { row: p.id, said: p.date, what: measureDisplay(p, s), due: isIso(p.due) ? p.due : null, kept: p.kept === true || checks.some((c) => c.kept === true), checks: checks.map((c) => c.id) }; + }), + span: { from: dates[0] ?? null, to: dates[dates.length - 1] ?? null }, + }; + + return { + version: MEASURE_SLICE_VERSION, + unit: s.unit, + scale: settings.scale, + asOfRender: settings.asOfRender, + scopes: settings.scopes, + events, + hidden, + state, + totals, + }; +} diff --git a/umtool/report-to-video/measure-slice.test.mjs b/umtool/report-to-video/measure-slice.test.mjs @@ -0,0 +1,229 @@ +// Tests for measure-slice.mjs: the odometer rule, a row's landing second, the +// state after each event, the totals, the settings, and the deck schedule's +// `measure`. Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + isRealtimeLoss, kindOf, lossRuns, measureOn, measureSettingsProblems, measureSlice, pinnedRows, spokenAt, spokenNumbers, + validateMeasureSettings, +} from "./measure-slice.mjs"; +import { estimateSchedule, validateChrome } from "./deck.mjs"; +import { scheduleSlices } from "./modules/index.mjs"; +import { validateClaims } from "./factcheck.mjs"; + +const SCHEMA = { + kind: "measure", + unit: "lb", + yMin: 210, + yMax: 400, + bandGapDays: 60, + tracks: [ + { key: "weight", role: "value", label: "Weight" }, + { key: "regime", role: "regime", label: "Diet", regimes: ["keto", "carnivore", "glp1", "off"] }, + { key: "drinking", role: "regime", label: "Drinking", regimes: ["dry", "drinking"] }, + ], + forms: ["current", "past", "delta", "goal", "goal_loss", "overweight_by", "status"], + regimes: [ + { key: "keto", label: "Keto" }, + { key: "carnivore", label: "Carnivore" }, + { key: "glp1", label: "GLP-1" }, + { key: "off", label: "No diet" }, + { key: "dry", label: "Dry" }, + { key: "drinking", label: "Drinking" }, + ], + fields: [{ key: "qualifier", label: "Bound", kind: "enum", options: [">", "<", "≈"], appliesTo: { scope: "weight" }, render: "cell" }], +}; + +/** An adjudicated row, the six fields filled with the boring answer. */ +const row = (o) => ({ + scope: "weight", scopeBasis: "his words", scopeConfidence: "read", valueKind: "uttered", flags: [], asOf: null, ...o, +}); + +const LEDGER = [ + row({ id: "w01", date: "2024-01-01", population: "past", asOf: "2008-06-30", value: 368, display: "368 lb", entryId: "c1" }), + row({ id: "w02", date: "2024-01-05", population: "delta", value: -9, display: "-9", entryId: "c1" }), + row({ id: "w03", date: "2024-02-01", population: "delta", value: -19.4, display: "-19.4" }), + // A loss in the past with no date to put in asOf: marked retro, not counted. + row({ id: "w04", date: "2024-02-02", population: "delta", value: -64, display: "-64", retro: true, entryId: "c2" }), + // A retrospective (asOf): not counted either. + row({ id: "w05", date: "2024-02-03", population: "delta", value: -45, asOf: "2020-01-01", display: "-45" }), + // > 60 days on: a new run… + row({ id: "w06", date: "2025-04-01", population: "delta", value: -7.5, display: "-7.5", entryId: "c3" }), + row({ id: "w07", date: "2025-05-01", population: "past", asOf: "2025-03-20", value: 349, display: "349 lb", entryId: "c3" }), + row({ id: "w08", date: "2025-05-10", population: "current", value: 335, display: "335 lb", entryId: "c4" }), + row({ id: "w09", date: "2025-05-20", population: "delta", value: -40, qualifier: "≈", display: "-40", entryId: "c4" }), + // …a lower figure later in the same run does not lower its peak. + row({ id: "w10", date: "2025-06-05", population: "delta", value: -29.2, display: "-29.2", entryId: "c5" }), + row({ id: "w11", date: "2025-06-06", population: "goal_loss", value: -65, display: "lose 65", deadline: "by Christmas", due: "2025-12-25", entryId: "c5" }), + // An explicit run: a claim his words put in the 2024 run (it does not open run 2). + row({ id: "w12", date: "2025-09-01", population: "delta", value: -30, run: 0, display: "-30" }), + row({ id: "r01", date: "2025-04-01", scope: "regime", population: "status", value: "keto", event: "start", display: "keto", entryId: "c3" }), + // "Off GLP-1" while on keto: keto stands (the off-scope fix). + row({ id: "r02", date: "2025-05-10", scope: "regime", population: "status", value: "glp1", event: "off", display: "off GLP-1", entryId: "c4" }), + row({ id: "r03", date: "2025-06-05", scope: "regime", population: "status", value: "carnivore", event: "start", display: "carnivore", entryId: "c5" }), + row({ id: "d01", date: "2025-05-10", scope: "drinking", population: "status", value: "dry", event: "start", display: "dry", entryId: "c4" }), + row({ id: "p01", date: "2025-06-05", population: "promise", value: null, display: "post a video of the scale", entryId: "c5" }), + row({ id: "p02", date: "2025-07-01", population: "promise_check", value: null, display: "pull up a video", promise: "p01" }), +]; + +const TIMELINE = [ + { type: "title", id: "z0", seconds: 4 }, + { type: "clip", id: "c1", video: "v1", start: 100, end: 120, quoteStart: 104 }, + { type: "clip", id: "c2", video: "v2", start: 10, end: 20, quoteStart: 12 }, + { type: "clip", id: "c3", video: "v3", start: 50, end: 70, quoteStart: 51 }, + { type: "clip", id: "c4", video: "v4", start: 0, end: 30, quoteStart: 2, claim: "w08" }, + { type: "clip", id: "c5", video: "v5", start: 200, end: 230, quoteStart: 205 }, +]; + +const SEGMENTS = [ + { id: "z0", start: 0, duration: 4 }, + { id: "c1", start: 4, duration: 20 }, + { id: "c2", start: 24, duration: 10 }, + { id: "c3", start: 34, duration: 20 }, + { id: "c4", start: 54, duration: 30 }, + { id: "c5", start: 84, duration: 30 }, +]; + +const manifest = (measure = { scopes: ["weight", "regime"], scale: { min: 220, max: 400 } }) => ({ + ledgerSchema: SCHEMA, + ledger: LEDGER, + timeline: TIMELINE, + render: { fps: 30, transition: 0, chrome: { engine: "hyperframes", layout: "deck", deck: { measure } } }, +}); + +// c4's words: "I weighed three hundred thirty five … I'm down about forty pounds". +const words = (list) => list.map(([text, start]) => ({ text, start, end: start + 0.2 })); +const WORDS = new Map([ + ["c4", { from: "words", words: words([["I", 3], ["weighed", 3.3], ["three", 4], ["hundred", 4.3], ["thirty", 4.6], ["five", 4.9], ["and", 10], ["I'm", 11], ["down", 11.3], ["about", 11.6], ["forty", 12], ["pounds", 12.4]]) }], +]); +const CLOCK = new Map([["c1", 100], ["c2", 10], ["c3", 50], ["c4", 0], ["c5", 200]]); + +test("the odometer: the highest real-time claim per run, summed; a gap past bandGapDays starts a run; a row's run wins", () => { + const { runs, runOf, total } = lossRuns(LEDGER, SCHEMA); + assert.deepEqual(runs.map((r) => [r.run, r.start, r.peak, r.row]), [[0, "2024-01-05", 30, "w12"], [1, "2025-04-01", 40, "w09"]]); + assert.equal(total, 70); + assert.equal(runOf.has("w04"), false, "a retro loss is not on the odometer"); + assert.equal(runOf.has("w05"), false, "a retrospective (asOf) is not either"); + assert.equal(runOf.get("w12"), 0, "his words put w12 in the first run"); + assert.equal(isRealtimeLoss(row({ population: "delta", value: 5 }), SCHEMA), false, "a gain is no loss"); + // Without the explicit run, w12 is three months after w10: a run of its own. + const plain = lossRuns(LEDGER.map((r) => (r.id === "w12" ? { ...r, run: undefined } : r)), SCHEMA); + assert.deepEqual(plain.runs.map((r) => r.peak), [19.4, 40, 30]); + assert.equal(plain.total, 89.4); +}); + +test("the numbers he says: digits and words, a point, a hundred", () => { + const ns = (s) => spokenNumbers(s.split(" ").map((text) => ({ text }))).map((n) => n.value); + assert.deepEqual(ns("at two hundred ninety one point five for a total"), [291.5]); + assert.deepEqual(ns("I'm down fifty eight point two"), [58.2]); + assert.deepEqual(ns("about a hundred and ten to go, 60 lbs and 291.5"), [110, 60, 291.5]); + assert.equal(spokenAt({ value: -40 }, "lost", WORDS.get("c4").words), 12); + assert.equal(spokenAt({ value: 335 }, "stated", WORDS.get("c4").words), 4); + assert.equal(spokenAt({ value: 999 }, "stated", WORDS.get("c4").words), null); + assert.equal(spokenAt({ value: "keto" }, "diet", words([["on", 1], ["keto", 2]]), -Infinity, SCHEMA), 2); + assert.equal(kindOf({ scope: "regime", population: "status" }, SCHEMA), "diet"); + assert.equal(kindOf({ population: "promise_check" }, SCHEMA), "promiseCheck"); +}); + +test("events: the rows the cut shows, in cut order, at the second the figure is said", () => { + const sl = measureSlice(manifest(), { segments: SEGMENTS }, { words: WORDS, clock: CLOCK, asOf: "2025-07-10" }); + assert.equal(sl.version, 1); + assert.deepEqual(sl.scopes, ["weight", "regime"]); + assert.deepEqual(sl.scale, { min: 220, max: 400 }); + assert.equal(sl.asOfRender, "2025-07-10"); + const at = Object.fromEntries(sl.events.map((e) => [e.row, [e.t, e.tFrom, e.segment]])); + // c4's two rows at their words: 54 + 4 and 54 + 12; its "off GLP-1" at the quote. + assert.deepEqual(at.w08, [58, "words", "c4"]); + assert.deepEqual(at.w09, [66, "words", "c4"]); + assert.deepEqual(at.r02, [56, "quote", "c4"]); + // No words: the quote's start, mapped through the clip's clock. + assert.deepEqual(at.w02, [8, "quote", "c1"]); + assert.deepEqual(at.w04, [26, "quote", "c2"]); + for (let i = 1; i < sl.events.length; i += 1) assert.ok(sl.events[i].t >= sl.events[i - 1].t, "in cut order"); + // Scopes: no drinking row, shown or hidden. + assert.ok(![...sl.events, ...sl.hidden].some((e) => e.row === "d01")); + // Hidden: in scope, on no entry of the cut. + assert.deepEqual(sl.hidden.map((e) => e.row), ["w03", "w05", "p02", "w12"]); + assert.ok(sl.hidden.every((e) => e.t === null)); + const w09 = sl.events.find((e) => e.row === "w09"); + assert.equal(w09.kind, "lost"); + assert.equal(w09.run, 1); + assert.equal(w09.qualifier, "≈"); + assert.equal(sl.events.find((e) => e.row === "w04").run, null, "retro: on screen, not on the odometer"); +}); + +test("state: after each event, from the shown rows only", () => { + const sl = measureSlice(manifest(), { segments: SEGMENTS }, { words: WORDS, clock: CLOCK, asOf: "2025-07-10" }); + assert.equal(sl.state.length, sl.events.length + 1); + assert.equal(sl.state[0].t, 0); + assert.equal(sl.state[0].current, null); + assert.deepEqual(sl.state[0].lost, { total: 0, runs: [] }); + const after = (id) => sl.state[sl.events.findIndex((e) => e.row === id) + 1]; + assert.deepEqual(after("w08").current, { value: 335, qualifier: null, row: "w08", date: "2025-05-10" }); + assert.deepEqual(after("w08").net, { from: { value: 368, date: "2008-06-30", row: "w01" }, to: { value: 335, date: "2025-05-10", row: "w08" }, value: -33 }); + // Keto stands through "off GLP-1". + assert.equal(after("r02").diet.regime, "keto"); + assert.equal(after("r02").diet.n, 1); + const last = sl.state[sl.state.length - 1]; + assert.equal(last.diet.regime, "carnivore"); + assert.equal(last.diet.n, 2); + // The odometer as the cut has shown it: w12 is hidden, so run 0's peak is the 9 shown. + assert.deepEqual(last.lost, { total: 49, runs: [{ run: 0, start: "2024-01-05", peak: 9, row: "w02" }, { run: 1, start: "2025-04-01", peak: 40, row: "w09" }] }); + for (let i = 1; i < sl.state.length; i += 1) assert.ok(sl.state[i].lost.total >= sl.state[i - 1].lost.total, "the odometer only goes up"); + // "Lose 65" against the start of its run: the 349 he remembers (asOf 20 March, 12 days before). + assert.deepEqual(last.goal, { value: 284, loss: 65, deadline: "by Christmas", due: "2025-12-25", row: "w11", display: "284 lb", base: { value: 349, row: "w07", from: "runStart" } }); + assert.deepEqual(last.goals, ["w11"]); + assert.deepEqual(last.remembered.map((r) => r.row), ["w01", "w07"]); + assert.deepEqual(last.promises, [{ row: "p01", said: "2025-06-05", what: "post a video of the scale", due: null, kept: false, checks: [] }]); +}); + +test("totals: the whole record in scope", () => { + const sl = measureSlice(manifest(), { segments: SEGMENTS }, { words: WORDS, clock: CLOCK, asOf: "2025-07-10" }); + const t = sl.totals; + assert.equal(t.lost, 70); + assert.equal(t.runs, 2); + assert.deepEqual(t.net, { from: 368, to: 335, value: -33, fromRow: "w01", toRow: "w08" }); + assert.equal(t.goals, 1); + assert.deepEqual(t.promises, [{ row: "p01", said: "2025-06-05", what: "post a video of the scale", due: null, kept: false, checks: ["p02"] }]); + assert.deepEqual(t.span, { from: "2008-06-30", to: "2025-09-01" }); + assert.deepEqual(t.under300, { said: 0, rows: [] }); + assert.equal(t.diets, 1, "keto -> carnivore is one change; off GLP-1 none"); +}); + +test("the settings: their shape, their scopes against the ledger, and when a cut writes a slice", () => { + assert.deepEqual(validateMeasureSettings(undefined), []); + assert.deepEqual(validateMeasureSettings({ scopes: ["weight"], scale: { min: 220, max: 400 }, asOf: "2026-11-05" }), []); + assert.deepEqual(validateMeasureSettings({ scopes: [], scale: { min: 4, max: 2 }, asOf: "Nov 5", x: 1 }), [ + "render.chrome.deck.measure.x is not a measure setting (scopes, scale, asOf)", + "render.chrome.deck.measure.scopes must be a list of the ledger's track keys (at least one)", + "render.chrome.deck.measure.scale.min must be below scale.max", + "render.chrome.deck.measure.asOf must be a date (YYYY-MM-DD)", + ]); + assert.deepEqual(measureSettingsProblems(manifest({ scopes: ["weight", "gym"] })), [ + 'render.chrome.deck.measure.scopes: "gym" is not a track of the ledger (weight, regime, drinking)', + ]); + assert.deepEqual(measureSettingsProblems({ ...manifest(), ledgerSchema: undefined }), ['render.chrome.deck.measure needs a measure ledger (ledgerSchema.kind "measure")']); + assert.equal(measureOn(manifest()), true); + assert.equal(measureOn({ ...manifest(), render: { chrome: { layout: "deck", deck: {} } } }), false); + assert.throws(() => measureSlice(manifest({ scopes: ["gym"] }), { segments: SEGMENTS }), /not a track/); + // The deck refuses a bad one where it refuses everything else. + const m = manifest({ scale: { min: 1 } }); + assert.match(validateChrome(m.render.chrome, m.render).join("\n"), /deck\.measure\.scale must be \{ min, max \}/); + // No scopes: every track. + assert.deepEqual(measureSlice(manifest({}), { segments: SEGMENTS }, { asOf: "2025-07-10" }).scopes, ["weight", "regime", "drinking"]); +}); + +test("the deck schedule carries `measure` only for a measure cut, and the slices hand it on", () => { + const m = manifest(); + const doc = estimateSchedule(m); + assert.ok(doc.measure, "a measure cut's schedule carries the slice"); + assert.equal(doc.measure.events.length, LEDGER.filter((r) => r.entryId && r.scope !== "drinking").length); + assert.equal(scheduleSlices(doc).measure, doc.measure); + const plain = estimateSchedule({ ...m, render: { ...m.render, chrome: { engine: "hyperframes", layout: "deck", deck: {} } } }); + assert.equal("measure" in plain, false, "no setting: the schedule it always was"); + assert.equal("measure" in scheduleSlices(plain), false); + // The ledger pin and the entryId name the same rows. + assert.deepEqual(pinnedRows(TIMELINE, LEDGER).get("c4"), ["w08", "w09", "r02", "d01"]); + assert.deepEqual(validateClaims(m), []); +}); diff --git a/umtool/report-to-video/measure-words.mjs b/umtool/report-to-video/measure-words.mjs @@ -0,0 +1,67 @@ +// The words a measure slice times its rows by (measure-slice.mjs): for each +// clip of the cut that shows a measure row, its words in SOURCE seconds and +// where they came from. Reads only. Plain ESM. +// +// The first of, per channels tree given (the project's own first -- its +// `provenance.channelsDir` or `.shadow-channels/` -- then the corpus): +// +// timed words clip-words.mjs clipWords: the word-timings sidecar, a +// whisper transcript's tokens, or the English caption track's +// word starts -> "words" +// the cues the cue record (`transcript.cues.json`), or the build's own +// cue reader (`cues(entry)`), each cue's words spread over it +// by their characters (fx.mjs fxWordsOf) -- an ESTIMATE, a +// second or so either way -> "cues" +// +// A clip with neither lands on its quoteStart (the slice's fallback). +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { clipWords } from "./clip-words.mjs"; +import { fxWordsOf } from "./fx.mjs"; +import { hasLocalMedia } from "./local-media.mjs"; + +/** + * @param {{ entries: object[], ids: Set<string>, provenance?: object, + * channelsDirs?: Array<string|null>, cues?: ((entry: object) => Promise<Array<{ start: number, end: number, text: string }>>) | null }} a + * `ids` the entries that show a measure row. + * @returns {Promise<Map<string, { words: Array<{ text: string, start: number, end: number }>, from: string }>>} + */ +export async function measureClipWords({ entries, ids, provenance = {}, channelsDirs = [], cues = null }) { + const out = new Map(); + const dirs = [...new Set(channelsDirs.filter(Boolean))]; + for (const e of entries) { + if (e?.type !== "clip" || !ids.has(e.id) || !Number.isFinite(e.start) || !Number.isFinite(e.end)) continue; + let got = null; + for (const dir of dirs) { + const w = await clipWords(e, provenance, e.start - 1, e.end + 1, { channelsDir: dir }).catch(() => null); + if (w?.words?.length) { got = { words: w.words.map((x) => ({ text: x.text, start: x.start, end: x.end ?? x.start })), from: "words" }; break; } + } + if (!got && !hasLocalMedia(e)) { + for (const dir of dirs) { + const spans = await cueFile(dir, e.channel ?? provenance.channelSlug, e.video); + const words = spans ? fxWordsOf(spans, e.start - 1, e.end + 1) : []; + if (words.length) { got = { words, from: "cues" }; break; } + } + } + if (!got && cues) { + const spans = await cues(e).catch(() => []); + const words = fxWordsOf(spans ?? [], e.start - 1, e.end + 1); + if (words.length) got = { words, from: "cues" }; + } + if (got) out.set(e.id, got); + } + return out; +} + +/** A video's cue record in a channels tree, or null. */ +async function cueFile(channelsDir, slug, video) { + if (!channelsDir || !slug || !video) return null; + try { + const dir = await resolveVideoDir(channelsDir, slug, video); + const doc = JSON.parse(await readFile(path.join(dir, "transcript.cues.json"), "utf8")); + return Array.isArray(doc?.cues) ? doc.cues : null; + } catch { + return null; + } +} diff --git a/umtool/report-to-video/modules/index.mjs b/umtool/report-to-video/modules/index.mjs @@ -129,6 +129,9 @@ export function scheduleSlices(doc) { ...(doc.flips ? { flips: doc.flips } : {}), ...(doc.stats ? { stats: doc.stats } : {}), ...(doc.fx ? { fx: doc.fx } : {}), + // The measure ledger's slice (measure-slice.mjs): every instrument module + // (dial, odometer, trail, goals, peak, promise, diet) reads it whole. + ...(doc.measure ? { measure: doc.measure } : {}), }; return out; } diff --git a/umtool/report-to-video/modules/rail.test.mjs b/umtool/report-to-video/modules/rail.test.mjs @@ -47,5 +47,5 @@ test("rail settings: spacing, pitch, and the deck's other keys refused by name", assert.equal(resolveDeck(render({})).pip.pitch, undefined, "no pitch unless set: the deck resolves as it did"); assert.equal(rail.resolve(render({ spacing: "pitch" })).pip.pitch, 28); assert.equal(rail.validate, settingsOf("rail").validate); - assert.deepEqual(SETTINGS.map((s) => s.id), ["stamp", "threads", "flips", "stats", "fx", "chat", "pair", "chapter", "status", "finale", "claims", "counter", "shell", "rail", "section-title", "subtitle", "qr", "popup-posts"]); + assert.deepEqual(SETTINGS.map((s) => s.id), ["stamp", "threads", "flips", "stats", "fx", "chat", "pair", "chapter", "status", "finale", "claims", "measure", "counter", "shell", "rail", "section-title", "subtitle", "qr", "popup-posts"]); }); diff --git a/umtool/report-to-video/modules/settings.mjs b/umtool/report-to-video/modules/settings.mjs @@ -19,6 +19,7 @@ import { validateFx } from "../fx.mjs"; import { validateChat } from "../chat.mjs"; import { validateChapter, validatePair, validateStatus } from "./story-settings.mjs"; import { MARKER_LEVELS, MARKER_LIMITS } from "../marker-limits.mjs"; +import { validateMeasureSettings } from "../measure-slice.mjs"; /** * Every deck setting and its default. A manifest names only what it changes; @@ -467,6 +468,9 @@ export const SETTINGS = Object.freeze([ validate: (v, { where }) => validateFinaleSettings(v, `${where}.finale`) }, { id: "claims", key: "deck.claims", configKey: "render.chrome.deck.claims", deck: true, validate: (v, { where }) => deckClaimShapeErrors(v, `${where}.claims`) }, + // The measure ledger's slice (measure-slice.mjs), which the instruments draw from. + { id: "measure", key: "deck.measure", configKey: "render.chrome.deck.measure", deck: true, + validate: (v, { where }) => validateMeasureSettings(v, `${where}.measure`) }, { id: "counter", key: "deck.counter", configKey: "render.chrome.deck.counter", deck: true, validate: (v, { chrome, render }) => validateCounter(v, { factcheck: chrome.factcheck, labelFits: (s, where) => counterLabelProblem(s, where, { fontBold: render.fontBold ?? null }), diff --git a/umtool/report-to-video/panel-model.mjs b/umtool/report-to-video/panel-model.mjs @@ -84,7 +84,7 @@ export function goalCell(row, base, schema) { * `display` is HIS words for it (the opening row's display), refreshed on * every opening row, `on` included: a report that the rule is holding is the * freshest thing he has said about what the rule is. `since` is when the - * regime in the cell opened (an `on` for the open regime keeps it). + * regime in the cell opened: an `on` for the open regime keeps it, a `start` opens it again. */ export function nextRegime(open, row, schema) { const s = measureSchema(schema); @@ -92,7 +92,9 @@ export function nextRegime(open, row, schema) { if (!R) return open; const at = plotDate(row); if (OPENING.has(row.event)) { - const same = open && open.key === R.key; + // `on` is a report that the rule holds: it keeps when the regime opened. + // `start` is the act -- a fresh start of the same regime opens it again. + const same = open && open.key === R.key && row.event === "on"; return { key: R.key, label: R.label, display: measureDisplay(row, s), at, since: same ? open.since : at, row: row.id }; } if (CLOSING.has(row.event)) {