@gentbajko/slopify 4.5.1 → 4.5.3

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 (54) hide show
  1. package/dist/edge/mcp/tools-runs.js +1 -1
  2. package/dist/extension/slopify-studio-chrome.zip +0 -0
  3. package/dist/extension/slopify-studio-firefox.zip +0 -0
  4. package/dist/kernel/db/migrations/0079-plan-history-indexes.sql +11 -0
  5. package/dist/kernel/db/migrations/0080-attempts-work-index.sql +4 -0
  6. package/dist/kernel/runner/providers.js +1 -1
  7. package/dist/kernel/runner/queue.js +31 -5
  8. package/dist/kernel/runner/work.js +52 -1
  9. package/dist/main.js +1 -1
  10. package/dist/patch-notes/4.5.2.md +17 -0
  11. package/dist/patch-notes/4.5.3.md +16 -0
  12. package/dist/patch-notes/index.json +12 -0
  13. package/dist/slices/article/production-note.js +75 -0
  14. package/dist/slices/loudness/level-pieces.js +12 -8
  15. package/dist/slices/loudness/sentence-level.js +35 -24
  16. package/dist/slices/narration/breaths-worker.js +126 -0
  17. package/dist/slices/narration/breaths.js +19 -81
  18. package/dist/slices/narration/clean-pieces.js +9 -10
  19. package/dist/slices/narration/pauses.js +18 -17
  20. package/dist/slices/narration/piece-jobs.js +54 -0
  21. package/dist/slices/narration/pronunciation.js +48 -3
  22. package/dist/slices/rebuild/admission-repo.js +14 -1
  23. package/dist/slices/rebuild/narration-history.js +72 -23
  24. package/dist/slices/rebuild/narration-reuse.js +16 -5
  25. package/dist/slices/rebuild/provided-review.js +14 -4
  26. package/dist/slices/rebuild/recipe-audio.js +6 -0
  27. package/dist/slices/rebuild/recipe-build.js +6 -2
  28. package/dist/slices/rebuild/recipe-document.js +23 -17
  29. package/dist/slices/rebuild/recipe-exports.js +8 -1
  30. package/dist/slices/rebuild/recipe-model.js +48 -4
  31. package/dist/slices/rebuild/recipe-preparation.js +28 -6
  32. package/dist/slices/rebuild/recipe-reviews.js +28 -24
  33. package/dist/slices/rebuild/recipe-save.js +16 -3
  34. package/dist/slices/rebuild/recipe-shorts.js +195 -8
  35. package/dist/slices/rebuild/recovery.js +35 -2
  36. package/dist/slices/rebuild/review-redo.js +15 -7
  37. package/dist/slices/rebuild/runtime-admission.js +5 -0
  38. package/dist/slices/rebuild/runtime-agent-review.js +4 -2
  39. package/dist/slices/rebuild/runtime-materialize.js +14 -0
  40. package/dist/slices/rebuild/runtime-plan.js +86 -40
  41. package/dist/slices/rebuild/runtime-provider.js +11 -4
  42. package/dist/slices/rebuild/runtime-review.js +3 -2
  43. package/dist/slices/rebuild/runtime-shorts.js +53 -13
  44. package/dist/slices/rebuild/transition-repo.js +13 -10
  45. package/dist/slices/reviews/outcome.js +5 -3
  46. package/dist/slices/reviews/repo.js +12 -0
  47. package/dist/slices/revisions/schema.js +1 -0
  48. package/dist/slices/revisions/view.js +3 -3
  49. package/dist/slices/settings/model.js +6 -2
  50. package/dist/slices/shorts/keep.js +37 -17
  51. package/dist/slices/storage/layout.js +15 -0
  52. package/dist/web/assets/{index-C0n0zeuZ.js → index-C8aMp7m3.js} +2 -2
  53. package/dist/web/index.html +1 -1
  54. package/package.json +1 -1
@@ -1,52 +1,48 @@
1
1
  import { mkdirSync, rmSync } from "node:fs";
2
- import { open, stat } from "node:fs/promises";
3
2
  import { join } from "node:path";
4
3
  import { errorText } from "../../kernel/errors.js";
5
4
  import { editSettings } from "../../kernel/ports/settings-places.js";
6
5
  import { runFfmpeg } from "../video/ffmpeg.js";
7
- import { breathRate, scanBreaths, softenChunk } from "./breaths-detect.js";
6
+ import { breathRate } from "./breaths-detect.js";
7
+ import { pcmWavHeader, softenPcmInWorker } from "./breaths-worker.js";
8
+ import { mapPieces } from "./piece-jobs.js";
8
9
  // Soften breaths, made in the join (`breaths-model.ts` says why there). Each narration piece is
9
10
  // decoded by ffmpeg to 16-bit mono PCM at 48 kHz in a file beside it, read once to find its
10
11
  // breaths (`breaths-detect.ts`) and once more to write it again as a WAV with them turned down. Both
11
- // reads go in chunks, so a long piece never sits in memory whole, and the detector yields to
12
- // the event loop as it goes, so the server stays responsive while it works. A piece without a
12
+ // reads go in chunks of a second, so a long piece never sits in memory whole, and both run in a
13
+ // worker thread (`breaths-worker.ts`), so the server stays responsive while it works and
14
+ // several pieces are worked on at once. A piece without a
13
15
  // breath is written again all the same: the join takes every piece in the one format.
14
- // ceiling: one second of audio per read.
15
- const chunkSamples = breathRate;
16
16
  export async function softenBreaths(run, files, directory) {
17
17
  mkdirSync(directory, { recursive: true, mode: 0o700 });
18
- const written = [];
19
- let softened = 0;
20
- let skipped = 0;
21
- for (const [index, file] of files.entries()) {
22
- run.signal.throwIfAborted();
18
+ // Several pieces at once (`piece-jobs.ts`); the counts are added up after, in order.
19
+ const pieces = await mapPieces(run, files, async (file, index, own) => {
23
20
  const name = `breaths-${String(index + 1).padStart(4, "0")}`;
24
21
  const raw = join(directory, `${name}.pcm`);
25
22
  const output = join(directory, `${name}.wav`);
26
23
  try {
27
24
  await runFfmpeg({
28
- bin: run.bin,
25
+ bin: own.bin,
29
26
  args: decodeArgs(file, raw),
30
- signal: run.signal,
31
- log: run.log,
27
+ signal: own.signal,
28
+ log: own.log,
32
29
  onProgress: () => { },
33
30
  });
34
- const scan = await scanBreaths(pcmChunks(raw));
35
- run.signal.throwIfAborted();
36
- await writeSoftened(raw, output, scan.stretches);
37
- softened += scan.stretches.length;
38
- skipped += scan.skipped.length;
31
+ const counts = await softenPcmInWorker({ raw, output }, own.signal);
32
+ return { output, ...counts };
39
33
  }
40
34
  catch (error) {
41
- if (run.signal.aborted)
35
+ if (own.signal.aborted)
42
36
  throw error;
43
37
  throw new Error(`Soften breaths could not process narration piece ${String(index + 1)} (${errorText(error)}), so the narration can't be joined together. Use Try again; if it fails again, turn off Soften breaths in ${editSettings.sound} and use Save changes, then use Download diagnostics in Settings and report it.`, { cause: error });
44
38
  }
45
39
  finally {
46
40
  rmSync(raw, { force: true });
47
41
  }
48
- written.push(output);
49
- }
42
+ });
43
+ const written = pieces.map((one) => one.output);
44
+ const softened = pieces.reduce((sum, one) => sum + one.softened, 0);
45
+ const skipped = pieces.reduce((sum, one) => sum + one.skipped, 0);
50
46
  return { files: written, softened, skipped };
51
47
  }
52
48
  export function decodeArgs(input, output) {
@@ -72,65 +68,7 @@ export function decodeArgs(input, output) {
72
68
  output,
73
69
  ];
74
70
  }
75
- async function* pcmChunks(path) {
76
- const handle = await open(path, "r");
77
- try {
78
- for (;;) {
79
- const chunk = await readChunk(handle);
80
- if (chunk === undefined)
81
- return;
82
- yield chunk;
83
- }
84
- }
85
- finally {
86
- await handle.close();
87
- }
88
- }
89
- async function readChunk(handle) {
90
- const buffer = Buffer.alloc(chunkSamples * 2);
91
- const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
92
- const samples = Math.floor(bytesRead / 2);
93
- if (samples === 0)
94
- return undefined;
95
- // A copy into its own buffer: Int16Array needs an aligned, even-length view.
96
- const out = new Int16Array(samples);
97
- for (let at = 0; at < samples; at += 1)
98
- out[at] = buffer.readInt16LE(at * 2);
99
- return out;
100
- }
101
- async function writeSoftened(raw, output, stretches) {
102
- const size = (await stat(raw)).size;
103
- const bytes = size - (size % 2);
104
- const target = await open(output, "w", 0o600);
105
- try {
106
- await target.write(wavHeader(bytes));
107
- let offset = 0;
108
- for await (const chunk of pcmChunks(raw)) {
109
- const soft = softenChunk(chunk, offset, stretches);
110
- // Typed arrays are little-endian on every platform Slopify ships for, as WAV is.
111
- await target.write(Buffer.from(soft.buffer, soft.byteOffset, soft.byteLength));
112
- offset += chunk.length;
113
- }
114
- }
115
- finally {
116
- await target.close();
117
- }
118
- }
119
71
  // A canonical 44-byte header: PCM, mono, 16-bit, 48 kHz.
120
72
  export function wavHeader(dataBytes) {
121
- const header = Buffer.alloc(44);
122
- header.write("RIFF", 0, "ascii");
123
- header.writeUInt32LE(36 + dataBytes, 4);
124
- header.write("WAVE", 8, "ascii");
125
- header.write("fmt ", 12, "ascii");
126
- header.writeUInt32LE(16, 16);
127
- header.writeUInt16LE(1, 20);
128
- header.writeUInt16LE(1, 22);
129
- header.writeUInt32LE(breathRate, 24);
130
- header.writeUInt32LE(breathRate * 2, 28);
131
- header.writeUInt16LE(2, 32);
132
- header.writeUInt16LE(16, 34);
133
- header.write("data", 36, "ascii");
134
- header.writeUInt32LE(dataBytes, 40);
135
- return header;
73
+ return pcmWavHeader(dataBytes, breathRate);
136
74
  }
@@ -5,6 +5,7 @@ import { editSettings } from "../../kernel/ports/settings-places.js";
5
5
  import { runFfmpeg } from "../video/ffmpeg.js";
6
6
  import { softenBreaths } from "./breaths.js";
7
7
  import { deEsser } from "./breaths-model.js";
8
+ import { mapPieces } from "./piece-jobs.js";
8
9
  export async function cleanPieces(run, files, directory, cleaning) {
9
10
  if (!cleaning.breaths && !cleaning.deEss)
10
11
  return undefined;
@@ -22,27 +23,25 @@ export async function cleanPieces(run, files, directory, cleaning) {
22
23
  }
23
24
  export async function deEssPieces(run, files, directory) {
24
25
  mkdirSync(directory, { recursive: true, mode: 0o700 });
25
- const written = [];
26
- for (const [index, file] of files.entries()) {
27
- run.signal.throwIfAborted();
26
+ // Several pieces at once, in order (`piece-jobs.ts`).
27
+ return mapPieces(run, files, async (file, index, own) => {
28
28
  const output = join(directory, `deess-${String(index + 1).padStart(4, "0")}.wav`);
29
29
  try {
30
30
  await runFfmpeg({
31
- bin: run.bin,
31
+ bin: own.bin,
32
32
  args: deEssArgs(file, output),
33
- signal: run.signal,
34
- log: run.log,
33
+ signal: own.signal,
34
+ log: own.log,
35
35
  onProgress: () => { },
36
36
  });
37
37
  }
38
38
  catch (error) {
39
- if (run.signal.aborted)
39
+ if (own.signal.aborted)
40
40
  throw error;
41
41
  throw new Error(`Soften S sounds could not process narration piece ${String(index + 1)} (${errorText(error)}), so the narration can't be joined together. Use Try again; if it fails again, turn off Soften S sounds in ${editSettings.sound} and use Save changes, then use Download diagnostics in Settings and report it.`, { cause: error });
42
42
  }
43
- written.push(output);
44
- }
45
- return written;
43
+ return output;
44
+ });
46
45
  }
47
46
  export function deEssFilter() {
48
47
  return `deesser=i=${String(deEsser.intensity)}:m=${String(deEsser.max)}:f=${String(deEsser.frequency)}`;
@@ -5,6 +5,7 @@ import { measureFile } from "../loudness/loudnorm.js";
5
5
  import { pieceLufs, pieceTruePeak } from "../loudness/model.js";
6
6
  import { probeDurationMs, runFfmpeg } from "../video/ffmpeg.js";
7
7
  import { sentences } from "./chunk.js";
8
+ import { mapPieces } from "./piece-jobs.js";
8
9
  // How long a stretch of text takes to say, in letters. Digits count as their words ("1982" as
9
10
  // "nineteen eighty two", English's being a fair measure for any language's), an IPA spelling's
10
11
  // slashes and stress marks count nothing, and a run of spacing counts one. Counted as written,
@@ -244,17 +245,16 @@ export async function measurePiece(run, file) {
244
245
  // Every piece's plan, from the pieces as spoken: silences inside, and at each piece's end what
245
246
  // the gap to the next piece lacks.
246
247
  export async function planPieces(run, pieces, settings) {
247
- const measured = [];
248
- for (const piece of pieces) {
249
- run.signal.throwIfAborted();
250
- const { durationSeconds, silences } = await measurePiece(run, piece.file);
251
- measured.push(planPauses({
248
+ // Measured several pieces at once, in order (`piece-jobs.ts`).
249
+ const measured = await mapPieces(run, pieces, async (piece, _index, own) => {
250
+ const { durationSeconds, silences } = await measurePiece(own, piece.file);
251
+ return planPauses({
252
252
  durationSeconds,
253
253
  silences,
254
254
  boundaries: textBoundaries(piece.text),
255
255
  settings,
256
- }));
257
- }
256
+ });
257
+ });
258
258
  return measured.map((pauses, at) => {
259
259
  const piece = pieces[at];
260
260
  const following = measured[at + 1];
@@ -269,25 +269,26 @@ export async function planPieces(run, pieces, settings) {
269
269
  // the spoken pieces.
270
270
  export async function applyPauses(run, files, plans, directory) {
271
271
  mkdirSync(directory, { recursive: true, mode: 0o700 });
272
- const written = [];
273
- let added = 0;
274
- for (const [index, file] of files.entries()) {
275
- run.signal.throwIfAborted();
272
+ // Several pieces at once, in order (`piece-jobs.ts`).
273
+ const written = await mapPieces(run, files, async (file, index, own) => {
276
274
  const plan = plans[index];
277
275
  const output = join(directory, `paced-${String(index + 1).padStart(4, "0")}.wav`);
278
276
  await runFfmpeg({
279
- bin: run.bin,
277
+ bin: own.bin,
280
278
  args: insertArgs(file, output, plan?.pauses.inserts ?? [], plan?.padEnd ?? 0, {
281
279
  sampleRate: 44100,
282
280
  channels: 1,
283
281
  }),
284
- signal: run.signal,
285
- log: run.log,
282
+ signal: own.signal,
283
+ log: own.log,
286
284
  onProgress: () => { },
287
285
  });
288
- added += (plan?.pauses.inserts.length ?? 0) + ((plan?.padEnd ?? 0) > 0 ? 1 : 0);
289
- written.push(output);
290
- }
286
+ return output;
287
+ });
288
+ const added = files.reduce((sum, _file, index) => {
289
+ const plan = plans[index];
290
+ return sum + (plan?.pauses.inserts.length ?? 0) + ((plan?.padEnd ?? 0) > 0 ? 1 : 0);
291
+ }, 0);
291
292
  return { files: written, added };
292
293
  }
293
294
  function round(value) {
@@ -0,0 +1,54 @@
1
+ import { availableParallelism } from "node:os";
2
+ // The join's per-piece steps (levelling, each sentence, breaths, S sounds, pauses) are each one
3
+ // ffmpeg audio pass per piece, and an audio pass keeps about one core busy. One piece at a time
4
+ // left a 32-thread machine nearly idle for most of an hour on a 2.5-hour narration, so several
5
+ // pieces go at once. Measured on 32 threads, eight real 4.8-minute pieces through levelling,
6
+ // each sentence, breaths, S sounds and pauses: one at a time 87 s, three 34 s, six 24 s, eight
7
+ // 14 s (all eight in one go), twelve 15 s. A render or another project's run may want the
8
+ // machine as well, so six is the most, and four cores are counted for each.
9
+ export const mostPieceJobs = 6;
10
+ const coresPerPieceJob = 4;
11
+ export function pieceJobs(cores = availableParallelism()) {
12
+ return Math.max(1, Math.min(mostPieceJobs, Math.floor(cores / coresPerPieceJob)));
13
+ }
14
+ // `work` over every item, at most `run.jobs` (else `pieceJobs()`) at once, the results in the
15
+ // items' order. Each call is given a run of its own whose signal ends with the caller's, so
16
+ // cancelling the run stops what is going and nothing new starts. The first failure stops the
17
+ // rest the same way, and once every call has ended that failure is the one thrown, not the
18
+ // cancellations it caused.
19
+ export async function mapPieces(run, items, work) {
20
+ run.signal.throwIfAborted();
21
+ const stop = new AbortController();
22
+ const follow = () => {
23
+ stop.abort(run.signal.reason);
24
+ };
25
+ run.signal.addEventListener("abort", follow, { once: true });
26
+ const own = { ...run, signal: stop.signal };
27
+ const results = new Array(items.length);
28
+ let next = 0;
29
+ let failed;
30
+ const runner = async () => {
31
+ while (failed === undefined && !stop.signal.aborted && next < items.length) {
32
+ const at = next;
33
+ next += 1;
34
+ try {
35
+ results[at] = await work(items[at], at, own);
36
+ }
37
+ catch (error) {
38
+ failed ??= { error };
39
+ stop.abort(error);
40
+ }
41
+ }
42
+ };
43
+ const limit = Math.max(1, Math.min(run.jobs ?? pieceJobs(), items.length));
44
+ try {
45
+ await Promise.all(Array.from({ length: limit }, runner));
46
+ }
47
+ finally {
48
+ run.signal.removeEventListener("abort", follow);
49
+ }
50
+ if (failed !== undefined)
51
+ throw failed.error;
52
+ run.signal.throwIfAborted();
53
+ return results;
54
+ }
@@ -186,8 +186,51 @@ export function skippedSpeakerPronunciationsNotice(rows) {
186
186
  return (`Speaker pronunciations: some entries are skipped and read as ordinary text (${parts.join(". ")}). ` +
187
187
  `The rest are used. To use them, fix those entries under Speakers → Pronunciations for that speaker (${createRows.narration}, or ${editSettings.narration}).`);
188
188
  }
189
- // Remembered (`kernel/remembered.ts`): every plan rebuild matches the whole narration again.
190
- export const pronunciationMatches = remembered(1024, (source, entries, possessives) => `${possessives === true ? "p" : "-"}\u0000${source}\u0000${JSON.stringify(entries)}`, matchPronunciations);
189
+ // Remembered: every plan rebuild matches the whole narration again, chunk by chunk, and a plan
190
+ // is derived again after every finished step of a run. The answers are kept per glossary, then
191
+ // per text. A glossary is known by its contents, written out once per array it arrives in (the
192
+ // parsed glossary is itself remembered, so that is once per glossary): writing it out and
193
+ // gluing it to the narration on every call was most of the matching's cost.
194
+ const glossaryKeys = new WeakMap();
195
+ function glossaryKey(entries) {
196
+ const known = glossaryKeys.get(entries);
197
+ // The length too: an array is never changed once made, but one that grew is not the same.
198
+ if (known !== undefined && known.length === entries.length)
199
+ return known.key;
200
+ const key = JSON.stringify(entries);
201
+ glossaryKeys.set(entries, { length: entries.length, key });
202
+ return key;
203
+ }
204
+ // ceilings: glossaries kept at once (a run's projects, each with and without possessives), and
205
+ // texts kept per glossary (a narration's chunks and the whole of it, for a few projects).
206
+ const rememberedGlossaries = 16;
207
+ const rememberedTexts = 1024;
208
+ // A pure function of a text and a glossary, remembered per glossary and then per text.
209
+ function byGlossary(work) {
210
+ const byKey = new Map();
211
+ return (source, entries, possessives = false) => {
212
+ const glossary = `${possessives ? "p" : "-"}${glossaryKey(entries)}`;
213
+ let texts = byKey.get(glossary);
214
+ if (texts === undefined) {
215
+ texts = new Map();
216
+ byKey.set(glossary, texts);
217
+ if (byKey.size > rememberedGlossaries)
218
+ byKey.delete(byKey.keys().next().value);
219
+ }
220
+ if (texts.has(source)) {
221
+ const known = texts.get(source);
222
+ texts.delete(source);
223
+ texts.set(source, known);
224
+ return known;
225
+ }
226
+ const value = work(source, entries, possessives);
227
+ texts.set(source, value);
228
+ if (texts.size > rememberedTexts)
229
+ texts.delete(texts.keys().next().value);
230
+ return value;
231
+ };
232
+ }
233
+ export const pronunciationMatches = byGlossary(matchPronunciations);
191
234
  function matchPronunciations(source, entries, possessives = false) {
192
235
  if (entries.length === 0)
193
236
  return [];
@@ -236,7 +279,9 @@ function withPossessive(ipa) {
236
279
  return `${ipa}\u026az`;
237
280
  return `${ipa}${"ptkfθ".includes(last) ? "s" : "z"}`;
238
281
  }
239
- export function pronunciationSpans(source, entries, possessives = false) {
282
+ // Remembered like the matches: asked again for every chunk each time the plan is derived.
283
+ export const pronunciationSpans = byGlossary(spansOf);
284
+ function spansOf(source, entries, possessives) {
240
285
  const spans = [];
241
286
  for (const match of pronunciationMatches(source, entries, possessives)) {
242
287
  const words = Array.from(source.slice(match.start, match.end).matchAll(/\S+/gu));
@@ -61,7 +61,7 @@ export function admitPreview(deps, input) {
61
61
  for (const recipe of snapshot.recipes) {
62
62
  const disposition = snapshot.dispositions.find((row) => row.key === recipe.key)?.disposition;
63
63
  const existing = deps.db
64
- .prepare(`SELECT w.id,w.state,w.recipe_context,r.piece_id,r.fingerprint FROM revision_work_reservations r JOIN revision_work w ON w.id=r.work_id WHERE r.revision_id=? AND r.work_key=?`)
64
+ .prepare(`SELECT w.id,w.state,w.recipe_context,r.piece_id,r.fingerprint,r.logical_key FROM revision_work_reservations r JOIN revision_work w ON w.id=r.work_id WHERE r.revision_id=? AND r.work_key=?`)
65
65
  .get(view.revision.id, recipe.key);
66
66
  if (disposition === "reuse") {
67
67
  bindNarrationReuse(deps, view, recipe, snapshot.ordinals[recipe.key] ?? 0);
@@ -71,6 +71,19 @@ export function admitPreview(deps, input) {
71
71
  typeof existing.recipe_context === "string" &&
72
72
  existing.state !== "done") {
73
73
  workIds.push(String(existing.id));
74
+ // A step reserved under a key this version's plan doesn't list (a picture check
75
+ // admitted under its own key before it was held to its picture) was never the
76
+ // version's to run, so a restart left it held for good: it takes the starting point a
77
+ // new one would. One whose key is listed under another fingerprint stays held below.
78
+ const own = typeof existing.logical_key === "string" ? existing.logical_key : recipe.key;
79
+ const anchorKey = reservationKey(recipe, view);
80
+ const anchor = snapshot.anchors[anchorKey];
81
+ if (view.revision.fingerprints[own] === undefined &&
82
+ anchor !== undefined &&
83
+ view.revision.fingerprints[anchorKey] === anchor)
84
+ deps.db
85
+ .prepare("UPDATE revision_work_reservations SET logical_key=?,desired_fingerprint=? WHERE revision_id=? AND work_key=? AND work_id=?")
86
+ .run(anchorKey, anchor, view.revision.id, recipe.key, String(existing.id));
74
87
  if (existing.state !== "running") {
75
88
  deps.db
76
89
  .prepare("UPDATE revision_work SET state='pending',dispatch_state='allowed',failure_reason=NULL,failure_kind=NULL,retry_at=NULL,auto_retries=0 WHERE id=?")
@@ -2,34 +2,83 @@ import { statSync } from "node:fs";
2
2
  import { z } from "zod";
3
3
  import { assetPathOrUndefined } from "../revisions/mutation-assets.js";
4
4
  import { stagePieceSchema } from "../revisions/schema.js";
5
- import { outputPath } from "../storage/layout.js";
5
+ import { outputPath, outputPaths } from "../storage/layout.js";
6
+ const keptRecords = new WeakMap();
7
+ const keptProjects = 12;
8
+ const historyRow = z.object({
9
+ id: z.string(),
10
+ piece_key: z.string(),
11
+ asset_id: z.string(),
12
+ fingerprint: z.string(),
13
+ path: z.string(),
14
+ });
15
+ const descriptorRow = z.object({ id: z.string(), descriptor: z.string() });
16
+ // Forgets every narration record kept for this database (tests compare against fresh reads).
17
+ export function forgetNarrationHistory(db) {
18
+ keptRecords.delete(db);
19
+ }
6
20
  export function retainedNarrationPieces(deps, projectId) {
7
- return deps.db
8
- .prepare(`SELECT p.piece_key,p.asset_id,p.fingerprint,p.descriptor,a.path FROM revision_pieces p
21
+ return retainedNarrationHistory(deps, projectId).pieces;
22
+ }
23
+ // The same, and a mark of it for the plan's key: which saved rows it holds, and whether each
24
+ // one's file is on disk. Two histories with one mark hold the same pieces, since a saved
25
+ // record never changes.
26
+ export function retainedNarrationHistory(deps, projectId) {
27
+ const rows = deps.db
28
+ .prepare(`SELECT p.id,p.piece_key,p.asset_id,p.fingerprint,a.path FROM revision_pieces p
9
29
  JOIN project_assets a ON a.id=p.asset_id AND a.project_id=p.project_id
10
30
  WHERE p.project_id=? AND p.stage_kind='audio' ORDER BY p.created_at,p.id`)
11
31
  .all(projectId)
12
- .map((value) => {
13
- const row = z
14
- .object({
15
- piece_key: z.string(),
16
- asset_id: z.string(),
17
- fingerprint: z.string(),
18
- descriptor: z.string(),
19
- path: z.string(),
20
- })
21
- .parse(value);
22
- return {
23
- key: row.piece_key,
24
- stageKind: "audio",
25
- assetId: row.asset_id,
26
- fingerprint: row.fingerprint,
27
- piece: stagePieceSchema.parse(JSON.parse(row.descriptor)),
28
- available: statSync(outputPath(deps.paths, projectId, row.path), {
29
- throwIfNoEntry: false,
30
- })?.isFile() === true,
31
- };
32
+ .map((value) => historyRow.parse(value));
33
+ const forDb = keptRecords.get(deps.db) ?? new Map();
34
+ keptRecords.set(deps.db, forDb);
35
+ const before = forDb.get(projectId);
36
+ // The columns read with the rows must still match the kept record, or it is read again.
37
+ const keeps = (row, kept) => kept !== undefined &&
38
+ kept.key === row.piece_key &&
39
+ kept.assetId === row.asset_id &&
40
+ kept.fingerprint === row.fingerprint;
41
+ const missing = rows.filter((row) => !keeps(row, before?.get(row.id)));
42
+ const descriptors = new Map();
43
+ const one = deps.db.prepare("SELECT id,descriptor FROM revision_pieces WHERE id=?");
44
+ for (const row of missing) {
45
+ const found = one.get(row.id);
46
+ if (found !== undefined) {
47
+ const parsed = descriptorRow.parse(found);
48
+ descriptors.set(parsed.id, parsed.descriptor);
49
+ }
50
+ }
51
+ const records = new Map();
52
+ const marks = [];
53
+ const pathOf = outputPaths(deps.paths, projectId);
54
+ const result = rows.flatMap((row) => {
55
+ const kept = before?.get(row.id);
56
+ let record;
57
+ if (kept !== undefined && keeps(row, kept))
58
+ record = kept;
59
+ else {
60
+ const descriptor = descriptors.get(row.id);
61
+ // Deleted between the two reads: it is no longer part of the history.
62
+ if (descriptor === undefined)
63
+ return [];
64
+ record = {
65
+ key: row.piece_key,
66
+ stageKind: "audio",
67
+ assetId: row.asset_id,
68
+ fingerprint: row.fingerprint,
69
+ piece: stagePieceSchema.parse(JSON.parse(descriptor)),
70
+ };
71
+ }
72
+ records.set(row.id, record);
73
+ const available = statSync(pathOf(row.path), { throwIfNoEntry: false })?.isFile() === true;
74
+ marks.push(`${row.id}:${row.piece_key}:${row.asset_id}:${row.fingerprint}:${available ? 1 : 0}`);
75
+ return [{ ...record, available }];
32
76
  });
77
+ forDb.delete(projectId);
78
+ forDb.set(projectId, records);
79
+ if (forDb.size > keptProjects)
80
+ forDb.delete(forDb.keys().next().value);
81
+ return { pieces: result, mark: marks.join("\n") };
33
82
  }
34
83
  export function referencedAssetsAvailable(deps, projectId, ids) {
35
84
  return ids.filter((id) => {
@@ -1,5 +1,18 @@
1
1
  import { z } from "zod";
2
2
  import { fingerprint } from "../../kernel/runner/work.js";
3
+ // The request a narration piece was voiced for, read from its payload once per piece: the plan
4
+ // asks it of every retained piece for every narration step it derives.
5
+ const requests = new WeakMap();
6
+ const requestPayload = z.object({ requestFingerprint: z.string() });
7
+ function requestOf(piece) {
8
+ const known = requests.get(piece);
9
+ if (known !== undefined)
10
+ return known;
11
+ const parsed = requestPayload.safeParse(JSON.parse(piece.payload ?? "null"));
12
+ const request = parsed.success ? parsed.data.requestFingerprint : null;
13
+ requests.set(piece, request);
14
+ return request;
15
+ }
3
16
  export function matchingNarrationPiece(recipe, pieces, available) {
4
17
  if (recipe.input.kind !== "tts")
5
18
  return undefined;
@@ -10,11 +23,9 @@ export function matchingNarrationPiece(recipe, pieces, available) {
10
23
  piece.assetId === null ||
11
24
  !available.has(piece.assetId))
12
25
  return false;
13
- const parsed = z
14
- .object({ requestFingerprint: z.string() })
15
- .safeParse(JSON.parse(piece.piece.payload ?? "null"));
16
- return (parsed.success &&
17
- parsed.data.requestFingerprint === recipe.requestFingerprint &&
26
+ const request = requestOf(piece.piece);
27
+ return (request !== null &&
28
+ request === recipe.requestFingerprint &&
18
29
  (noRegeneration || piece.fingerprint === recipe.fingerprint));
19
30
  });
20
31
  }
@@ -12,12 +12,22 @@ export function providedDependencyFingerprint(plan, key) {
12
12
  : null,
13
13
  });
14
14
  }
15
- export function applyProvidedReviews(db, revisionId, plan) {
16
- const approved = new Set(db
15
+ export function providedReviews(db, revisionId) {
16
+ return db
17
17
  .prepare("SELECT work_key,dependency_fingerprint FROM revision_provided_reviews WHERE revision_id=?")
18
18
  .all(revisionId)
19
- .filter((row) => row.dependency_fingerprint === providedDependencyFingerprint(plan, String(row.work_key)))
20
- .map((row) => String(row.work_key)));
19
+ .map((row) => ({
20
+ workKey: String(row.work_key),
21
+ dependencyFingerprint: row.dependency_fingerprint,
22
+ }));
23
+ }
24
+ export function applyProvidedReviews(db, revisionId, plan) {
25
+ return applyReviews(providedReviews(db, revisionId), plan);
26
+ }
27
+ export function applyReviews(reviews, plan) {
28
+ const approved = new Set(reviews
29
+ .filter((row) => row.dependencyFingerprint === providedDependencyFingerprint(plan, row.workKey))
30
+ .map((row) => row.workKey));
21
31
  return {
22
32
  ...plan,
23
33
  work: plan.work.map((row) => approved.has(row.key) && row.disposition === "review"
@@ -57,6 +57,7 @@ export function audioRecipes(context, text) {
57
57
  ]);
58
58
  let sections;
59
59
  let cards = [];
60
+ let bodyChunks;
60
61
  if (config.sources.audio === "provide") {
61
62
  body = recipe(context, "audio:provided", "audio", {
62
63
  kind: "provided",
@@ -96,6 +97,10 @@ export function audioRecipes(context, text) {
96
97
  pending = true;
97
98
  parts.push(...group);
98
99
  }
100
+ bodyChunks = groups.map((group, at) => ({
101
+ key: group.key,
102
+ text: transcripts[at]?.effective ?? group.text,
103
+ }));
99
104
  // A chunk with its own narration edit keeps the transcript in this form even once the article
100
105
  // says the same (`bodyNarrationGroups`), so the word timing made from it stays current.
101
106
  if (transcripts.some((row) => row.effective !== row.original) ||
@@ -239,6 +244,7 @@ export function audioRecipes(context, text) {
239
244
  levels,
240
245
  ...(sections === undefined ? {} : { sections }),
241
246
  ...(cards.length === 0 ? {} : { cards }),
247
+ ...(bodyChunks === undefined ? {} : { bodyChunks }),
242
248
  };
243
249
  }
244
250
  function effectiveText(context, key, original) {
@@ -6,7 +6,7 @@ import { editPlan } from "./recipe-edit.js";
6
6
  import { exportRecipes } from "./recipe-exports.js";
7
7
  import { fillPrompt } from "./recipe-keywords.js";
8
8
  import { linePlan } from "./recipe-lines.js";
9
- import { masterPlan } from "./recipe-loudness.js";
9
+ import { levelKey, masterPlan } from "./recipe-loudness.js";
10
10
  import { resourceIdentity } from "./recipe-model.js";
11
11
  import { imageReference, referenceRecipe } from "./recipe-reference.js";
12
12
  import { withReviews } from "./recipe-reviews.js";
@@ -78,7 +78,11 @@ function buildEach(plain) {
78
78
  ...youtube,
79
79
  ...socialRecipes(context, text),
80
80
  ...(reference === undefined ? [] : [reference]),
81
- ...shortsRecipes(context, exports, drawnFrom, audio.cards ?? [], masterPlan(context, audio.levels, "video"), appearance),
81
+ ...shortsRecipes(context, exports, drawnFrom, audio.cards ?? [], masterPlan(context, audio.levels, "video"), appearance, {
82
+ master: masterPlan(context, audio.levels.filter((level) => level.key === levelKey("body")), "video"),
83
+ chunks: audio.bodyChunks,
84
+ level: audio.levels.find((level) => level.key === levelKey("body")),
85
+ }),
82
86
  ...thumbnail,
83
87
  ...documentRecipes(context, text, thumbnail),
84
88
  ...visualAssets(context, visualRecipes(context.config, context.content, audio.mediaFingerprint, captions?.fingerprint ?? null, (images) => editPlan(context, exports, youtube, images, audio.cards ?? []), drawnFrom, timing === undefined ? null : resourceIdentity(context, timing), withLines(masterPlan(context, audio.levels, "video"), linePlan(context, timing)), scenes, appearance, (text) => fillPrompt(context, text, "image"))),