@bendyline/squisq 1.5.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -10
- package/dist/{Doc-BBVGq1_9.d.ts → Doc-ylqWKDc_.d.ts} +248 -37
- package/dist/{ImageEditDoc-FuyGtt6o.d.ts → ImageEditDoc-D828IXJ1.d.ts} +1 -1
- package/dist/annotationCoercion-Dr_DY9Hx.d.ts +86 -0
- package/dist/{chunk-VWUFZ6ZG.js → chunk-3E5F2XMR.js} +2 -29
- package/dist/chunk-3E5F2XMR.js.map +1 -0
- package/dist/chunk-4X3JQXNM.js +35 -0
- package/dist/chunk-4X3JQXNM.js.map +1 -0
- package/dist/{chunk-2OIBZYKP.js → chunk-5DKBFXPY.js} +31 -121
- package/dist/chunk-5DKBFXPY.js.map +1 -0
- package/dist/{chunk-DLXZMS5K.js → chunk-5J4HKRJF.js} +51 -3
- package/dist/chunk-5J4HKRJF.js.map +1 -0
- package/dist/chunk-5UYI3RJB.js +2503 -0
- package/dist/chunk-5UYI3RJB.js.map +1 -0
- package/dist/{chunk-TEEEILMP.js → chunk-66QO7XFB.js} +19 -292
- package/dist/chunk-66QO7XFB.js.map +1 -0
- package/dist/{chunk-KKNUBQ6Y.js → chunk-6PJRB2CF.js} +156 -91
- package/dist/chunk-6PJRB2CF.js.map +1 -0
- package/dist/{chunk-HWVFJAAH.js → chunk-AMIR72JP.js} +28 -10
- package/dist/chunk-AMIR72JP.js.map +1 -0
- package/dist/chunk-FVJUUTEM.js +74 -0
- package/dist/chunk-FVJUUTEM.js.map +1 -0
- package/dist/{chunk-LH7I6SH7.js → chunk-GF3BVNLU.js} +6360 -5723
- package/dist/chunk-GF3BVNLU.js.map +1 -0
- package/dist/{chunk-Q3ROPT5H.js → chunk-GZY66SDN.js} +1 -1
- package/dist/{chunk-Q3ROPT5H.js.map → chunk-GZY66SDN.js.map} +1 -1
- package/dist/chunk-JOQYPRDZ.js +127 -0
- package/dist/chunk-JOQYPRDZ.js.map +1 -0
- package/dist/{chunk-A4O7GIWE.js → chunk-LYNJEOAC.js} +10 -73
- package/dist/chunk-LYNJEOAC.js.map +1 -0
- package/dist/{chunk-LDQ2HJIX.js → chunk-PXLVXTLW.js} +252 -54
- package/dist/chunk-PXLVXTLW.js.map +1 -0
- package/dist/{chunk-TQWLI6S2.js → chunk-Q7LROV2H.js} +4 -2
- package/dist/{chunk-TQWLI6S2.js.map → chunk-Q7LROV2H.js.map} +1 -1
- package/dist/{chunk-T5UK6YOB.js → chunk-QTSJOY54.js} +60 -17
- package/dist/chunk-QTSJOY54.js.map +1 -0
- package/dist/chunk-QVANWDPH.js +2358 -0
- package/dist/chunk-QVANWDPH.js.map +1 -0
- package/dist/{chunk-6ATE2PSM.js → chunk-R2GC6RLD.js} +7 -7
- package/dist/chunk-R2GC6RLD.js.map +1 -0
- package/dist/chunk-R2YZTCLO.js +292 -0
- package/dist/chunk-R2YZTCLO.js.map +1 -0
- package/dist/chunk-S7A5D7ZJ.js +174 -0
- package/dist/chunk-S7A5D7ZJ.js.map +1 -0
- package/dist/chunk-T3TI7GSZ.js +884 -0
- package/dist/chunk-T3TI7GSZ.js.map +1 -0
- package/dist/{chunk-RUDYOTA6.js → chunk-TUWMK62B.js} +110 -4
- package/dist/chunk-TUWMK62B.js.map +1 -0
- package/dist/{chunk-IMSCRLLV.js → chunk-VR7UPJ7C.js} +35 -25
- package/dist/chunk-VR7UPJ7C.js.map +1 -0
- package/dist/doc/index.d.ts +2334 -5
- package/dist/doc/index.js +134 -34
- package/dist/generate/index.d.ts +7 -2
- package/dist/generate/index.js +1 -1
- package/dist/imageEdit/index.d.ts +9 -6
- package/dist/imageEdit/index.js +3 -3
- package/dist/index.d.ts +12 -10
- package/dist/index.js +253 -81
- package/dist/jsonForm/index.d.ts +7 -3
- package/dist/jsonForm/index.js +9 -4
- package/dist/markdown/index.d.ts +6 -70
- package/dist/markdown/index.js +13 -9
- package/dist/narration/index.d.ts +618 -0
- package/dist/narration/index.js +82 -0
- package/dist/recommend/index.d.ts +15 -1
- package/dist/recommend/index.js +2 -2
- package/dist/schemas/index.d.ts +28 -6
- package/dist/schemas/index.js +15 -13
- package/dist/spatial/index.d.ts +0 -1
- package/dist/spatial/index.js +1 -1
- package/dist/storage/index.js +1 -1
- package/dist/{themeLibrary-CehcJhzz.d.ts → themeLibrary-RjVgLpUi.d.ts} +10 -11
- package/dist/timing/index.js +5 -3
- package/dist/transform/index.d.ts +35 -24
- package/dist/transform/index.js +9 -10
- package/dist/{types-DlAZ7MW4.d.ts → types-BwMPl2CB.d.ts} +1 -1
- package/dist/{types-D98li1gV.d.ts → types-C4kiRn_k.d.ts} +3 -1
- package/dist/versions/index.d.ts +2 -1
- package/dist/versions/index.js +2 -2
- package/package.json +6 -6
- package/src/__tests__/applyNarrationTiming.test.ts +190 -0
- package/src/__tests__/applyRenderStyle.test.ts +3 -3
- package/src/__tests__/asciiDiagramBattle.test.ts +246 -0
- package/src/__tests__/asciiDiagramDetect.test.ts +162 -0
- package/src/__tests__/asciiDiagramMapping.test.ts +38 -0
- package/src/__tests__/asciiDiagramParse.test.ts +233 -0
- package/src/__tests__/asciiDiagramPipeline.test.ts +273 -0
- package/src/__tests__/asciiDiagramRender.test.ts +162 -0
- package/src/__tests__/asciiDiagramRepair.test.ts +84 -0
- package/src/__tests__/asciiTimelineDetect.test.ts +157 -0
- package/src/__tests__/asciiTimelineParse.test.ts +205 -0
- package/src/__tests__/asciiTimelinePipeline.test.ts +349 -0
- package/src/__tests__/asciiTimelineRender.test.ts +376 -0
- package/src/__tests__/attrTokens.test.ts +5 -0
- package/src/__tests__/contentContainer.test.ts +43 -0
- package/src/__tests__/coverBlock.test.ts +33 -2
- package/src/__tests__/customTemplatesFrontmatter.test.ts +0 -15
- package/src/__tests__/dataTable.test.ts +25 -15
- package/src/__tests__/diagramBlock.test.ts +3 -3
- package/src/__tests__/diagramText.test.ts +26 -0
- package/src/__tests__/docToMarkdownMedia.test.ts +83 -0
- package/src/__tests__/drawingBlock.test.ts +3 -3
- package/src/__tests__/fixtures/asciiDiagramBattle.ts +512 -0
- package/src/__tests__/fixtures/asciiDiagrams.ts +287 -0
- package/src/__tests__/fixtures/asciiTimelines.ts +35 -0
- package/src/__tests__/fixtures/treeviewFixtures.ts +243 -0
- package/src/__tests__/getLayers.test.ts +32 -18
- package/src/__tests__/getLayersFallback.test.ts +8 -8
- package/src/__tests__/imageEditVersions.test.ts +2 -0
- package/src/__tests__/jsonForm.pointer.test.ts +47 -1
- package/src/__tests__/layoutBlock.test.ts +3 -3
- package/src/__tests__/majorApiTypes.test.ts +18 -0
- package/src/__tests__/markdown.test.ts +41 -0
- package/src/__tests__/markdownToDoc.test.ts +5 -2
- package/src/__tests__/matchFontFamily.test.ts +114 -0
- package/src/__tests__/materializeBlockLayers.test.ts +135 -0
- package/src/__tests__/materializeTestUtils.ts +17 -0
- package/src/__tests__/narrationAlign.test.ts +150 -0
- package/src/__tests__/narrationFeatures.test.ts +71 -0
- package/src/__tests__/narrationNuclei.test.ts +45 -0
- package/src/__tests__/narrationPacing.test.ts +189 -0
- package/src/__tests__/narrationScript.test.ts +149 -0
- package/src/__tests__/narrationSessionRepro.test.ts +62 -0
- package/src/__tests__/narrationSidecar.test.ts +88 -0
- package/src/__tests__/narrationSyllables.test.ts +65 -0
- package/src/__tests__/narrationTestSignals.ts +167 -0
- package/src/__tests__/narrationVad.test.ts +66 -0
- package/src/__tests__/resolveDocTheme.test.ts +16 -2
- package/src/__tests__/rootExports.test.ts +18 -0
- package/src/__tests__/scopedContentContainer.test.ts +20 -0
- package/src/__tests__/shapeGeometry.test.ts +49 -0
- package/src/__tests__/templateAnnotationParse.test.ts +10 -0
- package/src/__tests__/templateInputs.test.ts +69 -0
- package/src/__tests__/templateMetadata.test.ts +2 -1
- package/src/__tests__/templates.test.ts +143 -17
- package/src/__tests__/themeCompile.test.ts +49 -22
- package/src/__tests__/transformProvenance.test.ts +160 -0
- package/src/__tests__/transformV2.test.ts +40 -14
- package/src/__tests__/treeviewBattle.test.ts +76 -0
- package/src/__tests__/treeviewDetect.test.ts +168 -0
- package/src/__tests__/treeviewParse.test.ts +118 -0
- package/src/__tests__/treeviewPipeline.test.ts +183 -0
- package/src/__tests__/treeviewRender.test.ts +91 -0
- package/src/__tests__/versions.test.ts +44 -0
- package/src/doc/applyNarrationTiming.ts +244 -0
- package/src/doc/asciiDiagram/chars.ts +210 -0
- package/src/doc/asciiDiagram/detect.ts +175 -0
- package/src/doc/asciiDiagram/index.ts +38 -0
- package/src/doc/asciiDiagram/mapping.ts +225 -0
- package/src/doc/asciiDiagram/parse.ts +1095 -0
- package/src/doc/asciiDiagram/render.ts +963 -0
- package/src/doc/asciiDiagram/repair.ts +400 -0
- package/src/doc/asciiDiagram/types.ts +65 -0
- package/src/doc/asciiTimeline/detect.ts +138 -0
- package/src/doc/asciiTimeline/index.ts +26 -0
- package/src/doc/asciiTimeline/mapping.ts +43 -0
- package/src/doc/asciiTimeline/parse.ts +870 -0
- package/src/doc/asciiTimeline/render.ts +427 -0
- package/src/doc/asciiTimeline/types.ts +73 -0
- package/src/doc/asciiTimeline/wrappedFlow.ts +427 -0
- package/src/doc/audioMapping.ts +60 -46
- package/src/doc/customTemplatesFrontmatter.ts +0 -41
- package/src/doc/docToMarkdown.ts +126 -39
- package/src/doc/index.ts +76 -4
- package/src/doc/markdownToDoc.ts +135 -1
- package/src/doc/materializeBlockLayers.ts +304 -0
- package/src/doc/mediaAnnotations.ts +20 -0
- package/src/doc/resolveDocTheme.ts +8 -7
- package/src/doc/templateInputs.ts +185 -2
- package/src/doc/templates/__tests__/customTemplateRegistry.test.ts +22 -8
- package/src/doc/templates/coverBlock.ts +49 -13
- package/src/doc/templates/diagramBlock.ts +237 -38
- package/src/doc/templates/drawingBlock.ts +2 -2
- package/src/doc/templates/fallbackBlock.ts +1 -1
- package/src/doc/templates/index.ts +134 -279
- package/src/doc/templates/inputDescriptors.ts +20 -1
- package/src/doc/templates/metadata.ts +10 -0
- package/src/doc/templates/persistentLayers.ts +12 -126
- package/src/doc/templates/registry.ts +88 -0
- package/src/doc/templates/templateNames.ts +22 -0
- package/src/doc/templates/timelineBlock.ts +613 -0
- package/src/doc/templates/treeBlock.ts +131 -0
- package/src/doc/treeview/chars.ts +72 -0
- package/src/doc/treeview/detect.ts +145 -0
- package/src/doc/treeview/index.ts +30 -0
- package/src/doc/treeview/mapping.ts +95 -0
- package/src/doc/treeview/parse.ts +201 -0
- package/src/doc/treeview/render.ts +41 -0
- package/src/doc/treeview/types.ts +43 -0
- package/src/doc/utils/applyRenderStyle.ts +2 -9
- package/src/doc/utils/diagramText.ts +78 -0
- package/src/doc/utils/shapeGeometry.ts +157 -7
- package/src/doc/validate.ts +1 -1
- package/src/generate/templateMapper.ts +7 -0
- package/src/imageEdit/export.ts +6 -5
- package/src/imageEdit/versionPaths.ts +13 -26
- package/src/imageEdit/versions.ts +21 -100
- package/src/index.ts +1 -0
- package/src/internal/immutable.ts +58 -0
- package/src/jsonForm/index.ts +9 -1
- package/src/jsonForm/pointer.ts +68 -23
- package/src/markdown/attrTokens.ts +7 -5
- package/src/markdown/convert.ts +11 -1
- package/src/markdown/index.ts +1 -0
- package/src/markdown/stringify.ts +4 -9
- package/src/markdown/utils.ts +36 -14
- package/src/narration/align.ts +514 -0
- package/src/narration/features.ts +231 -0
- package/src/narration/index.ts +86 -0
- package/src/narration/nuclei.ts +118 -0
- package/src/narration/pacing.ts +211 -0
- package/src/narration/script.ts +239 -0
- package/src/narration/session.ts +100 -0
- package/src/narration/sidecar.ts +187 -0
- package/src/narration/syllables.ts +85 -0
- package/src/narration/trace.ts +50 -0
- package/src/narration/types.ts +299 -0
- package/src/narration/vad.ts +131 -0
- package/src/recommend/numberHighlight.ts +25 -0
- package/src/recommend/templates.ts +108 -12
- package/src/schemas/BlockTemplates.ts +156 -7
- package/src/schemas/Doc.ts +72 -9
- package/src/schemas/Media.ts +12 -2
- package/src/schemas/Theme.ts +45 -25
- package/src/schemas/Viewport.ts +2 -2
- package/src/schemas/fontStacks.ts +79 -0
- package/src/schemas/themeCompile.ts +15 -0
- package/src/schemas/themeConstants.ts +2 -0
- package/src/schemas/themeLibrary.ts +25 -19
- package/src/schemas/themeValidator.ts +1 -1
- package/src/spatial/Geohash.ts +0 -3
- package/src/storage/ContentContainer.ts +17 -9
- package/src/storage/ScopedContentContainer.ts +45 -15
- package/src/transform/applyTransform.ts +5 -5
- package/src/transform/index.ts +3 -1
- package/src/transform/registry.ts +169 -49
- package/src/transform/templateSelector.ts +21 -2
- package/src/transform/timingAllocator.ts +152 -21
- package/src/transform/types.ts +14 -1
- package/src/versions/gitignore.ts +34 -0
- package/src/versions/index.ts +2 -0
- package/src/versions/operations.ts +18 -104
- package/src/versions/paths.ts +13 -28
- package/src/versions/snapshotStore.ts +202 -0
- package/src/versions/types.ts +3 -1
- package/dist/chunk-2OIBZYKP.js.map +0 -1
- package/dist/chunk-6ATE2PSM.js.map +0 -1
- package/dist/chunk-A4O7GIWE.js.map +0 -1
- package/dist/chunk-DLXZMS5K.js.map +0 -1
- package/dist/chunk-HWVFJAAH.js.map +0 -1
- package/dist/chunk-IMSCRLLV.js.map +0 -1
- package/dist/chunk-JELIRVDP.js +0 -24
- package/dist/chunk-JELIRVDP.js.map +0 -1
- package/dist/chunk-KKNUBQ6Y.js.map +0 -1
- package/dist/chunk-LDQ2HJIX.js.map +0 -1
- package/dist/chunk-LH7I6SH7.js.map +0 -1
- package/dist/chunk-RUDYOTA6.js.map +0 -1
- package/dist/chunk-T5UK6YOB.js.map +0 -1
- package/dist/chunk-TEEEILMP.js.map +0 -1
- package/dist/chunk-UY7KGQ5R.js +0 -192
- package/dist/chunk-UY7KGQ5R.js.map +0 -1
- package/dist/chunk-VLJJHDAC.js +0 -218
- package/dist/chunk-VLJJHDAC.js.map +0 -1
- package/dist/chunk-VWUFZ6ZG.js.map +0 -1
- package/dist/story/index.d.ts +0 -1777
- package/dist/story/index.js +0 -273
- package/src/doc/getLayers.ts +0 -195
- /package/dist/{story → narration}/index.js.map +0 -0
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Teleprompter script model: a Doc flattened into an ordered word-token
|
|
3
|
+
* stream with per-block ranges.
|
|
4
|
+
*
|
|
5
|
+
* `sourceText` is the canonical narration text — it is stored verbatim
|
|
6
|
+
* in the timing sidecar, and every token/block `charOffset` indexes into
|
|
7
|
+
* it. Determinism matters: the same Doc always builds a byte-identical
|
|
8
|
+
* script, because sidecar↔doc matching later compares slices of this
|
|
9
|
+
* exact string.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { Block, Doc } from '../schemas/Doc.js';
|
|
13
|
+
import { flattenRenderableBlocks, getBlockBodyText } from '../doc/markdownToDoc.js';
|
|
14
|
+
import { estimateSpokenWordCount } from '../timing/narrationTiming.js';
|
|
15
|
+
import { estimateSyllables } from './syllables.js';
|
|
16
|
+
import type { NarrationScript, ScriptBlockRange, ScriptToken, WordTiming } from './types.js';
|
|
17
|
+
|
|
18
|
+
export interface BuildScriptOptions {
|
|
19
|
+
/** Include block headings as spoken text (readers usually speak them). Default true. */
|
|
20
|
+
includeTitles?: boolean;
|
|
21
|
+
/** Separator joining block texts inside `sourceText`. Default '\n\n'. */
|
|
22
|
+
blockSeparator?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Spoken text of one block: optional title line + body plain text. */
|
|
26
|
+
function blockSpokenText(block: Block, includeTitles: boolean): string {
|
|
27
|
+
const title = includeTitles && block.title ? block.title.trim() : '';
|
|
28
|
+
const body = getBlockBodyText(block);
|
|
29
|
+
if (title && body) return `${title}\n${body}`;
|
|
30
|
+
return title || body;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Build the narration script for a doc. Blocks with no spoken text
|
|
35
|
+
* (pure-media sections, container-template children) contribute no
|
|
36
|
+
* tokens and no block range.
|
|
37
|
+
*/
|
|
38
|
+
export function buildNarrationScript(doc: Doc, options?: BuildScriptOptions): NarrationScript {
|
|
39
|
+
const includeTitles = options?.includeTitles ?? true;
|
|
40
|
+
const separator = options?.blockSeparator ?? '\n\n';
|
|
41
|
+
|
|
42
|
+
const pieces: Array<{ blockId: string; heading?: string; text: string }> = [];
|
|
43
|
+
for (const block of flattenRenderableBlocks(doc.blocks)) {
|
|
44
|
+
const text = blockSpokenText(block, includeTitles);
|
|
45
|
+
if (!text) continue;
|
|
46
|
+
pieces.push({
|
|
47
|
+
blockId: block.id,
|
|
48
|
+
heading: block.title || undefined,
|
|
49
|
+
text,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
let sourceText = '';
|
|
54
|
+
const blocks: ScriptBlockRange[] = [];
|
|
55
|
+
for (let i = 0; i < pieces.length; i++) {
|
|
56
|
+
if (i > 0) sourceText += separator;
|
|
57
|
+
const charStart = sourceText.length;
|
|
58
|
+
sourceText += pieces[i].text;
|
|
59
|
+
blocks.push({
|
|
60
|
+
blockId: pieces[i].blockId,
|
|
61
|
+
...(pieces[i].heading !== undefined ? { heading: pieces[i].heading } : {}),
|
|
62
|
+
tokenStart: 0,
|
|
63
|
+
tokenEnd: 0,
|
|
64
|
+
charStart,
|
|
65
|
+
charEnd: sourceText.length,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Tokenize with a single left-to-right scan so charOffsets are exact.
|
|
70
|
+
const tokens: ScriptToken[] = [];
|
|
71
|
+
const tokenRe = /\S+/g;
|
|
72
|
+
let blockIndex = 0;
|
|
73
|
+
let match: RegExpExecArray | null;
|
|
74
|
+
while ((match = tokenRe.exec(sourceText)) !== null) {
|
|
75
|
+
const charOffset = match.index;
|
|
76
|
+
const charEnd = charOffset + match[0].length;
|
|
77
|
+
while (blockIndex < blocks.length - 1 && charOffset >= blocks[blockIndex].charEnd) {
|
|
78
|
+
blockIndex++;
|
|
79
|
+
}
|
|
80
|
+
// A token with no letters or digits (a standalone em-dash, bullet, …)
|
|
81
|
+
// is punctuation, not a word: it displays but is never spoken.
|
|
82
|
+
const spoken = hasSpokenContent(match[0]);
|
|
83
|
+
tokens.push({
|
|
84
|
+
text: match[0],
|
|
85
|
+
charOffset,
|
|
86
|
+
charEnd,
|
|
87
|
+
blockId: blocks[blockIndex]?.blockId ?? '',
|
|
88
|
+
blockIndex,
|
|
89
|
+
syllables: spoken ? estimateSyllables(match[0]) : 0,
|
|
90
|
+
spokenWordEquiv: spoken ? estimateSpokenWordCount(stripBoundaryPunct(match[0])) : 0,
|
|
91
|
+
pauseAfter: 0,
|
|
92
|
+
spoken,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Token ranges per block.
|
|
97
|
+
for (const range of blocks) {
|
|
98
|
+
range.tokenStart = tokens.length;
|
|
99
|
+
range.tokenEnd = 0;
|
|
100
|
+
}
|
|
101
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
102
|
+
const range = blocks[tokens[i].blockIndex];
|
|
103
|
+
if (range) {
|
|
104
|
+
if (i < range.tokenStart) range.tokenStart = i;
|
|
105
|
+
range.tokenEnd = i + 1;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
for (const range of blocks) {
|
|
109
|
+
if (range.tokenStart > range.tokenEnd) {
|
|
110
|
+
// No tokens landed in this range (cannot happen for non-empty text,
|
|
111
|
+
// but keep the invariant tokenStart ≤ tokenEnd).
|
|
112
|
+
range.tokenStart = range.tokenEnd;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Pause classes: block boundary > paragraph break > clause punctuation.
|
|
117
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
118
|
+
const token = tokens[i];
|
|
119
|
+
const next = tokens[i + 1];
|
|
120
|
+
if (!next || next.blockIndex !== token.blockIndex) {
|
|
121
|
+
token.pauseAfter = 3;
|
|
122
|
+
} else if (sourceText.slice(token.charEnd, next.charOffset).includes('\n')) {
|
|
123
|
+
// getBlockBodyText joins paragraphs/list items with a single '\n',
|
|
124
|
+
// so ANY newline in the inter-token gap is a paragraph-class pause.
|
|
125
|
+
token.pauseAfter = 2;
|
|
126
|
+
} else if (endsWithClausePunctuation(token.text)) {
|
|
127
|
+
token.pauseAfter = 1;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const cumulativeSyllables = new Array<number>(tokens.length + 1);
|
|
132
|
+
cumulativeSyllables[0] = 0;
|
|
133
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
134
|
+
cumulativeSyllables[i + 1] = cumulativeSyllables[i] + tokens[i].syllables;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
sourceText,
|
|
139
|
+
tokens,
|
|
140
|
+
blocks,
|
|
141
|
+
totalSyllables: cumulativeSyllables[tokens.length],
|
|
142
|
+
cumulativeSyllables,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const TRAILING_CLOSERS = /["')\]}»”’]+$/;
|
|
147
|
+
|
|
148
|
+
/** True when a token carries at least one letter or digit (i.e. is spoken). */
|
|
149
|
+
function hasSpokenContent(token: string): boolean {
|
|
150
|
+
return /[\p{L}\p{N}]/u.test(token);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function stripBoundaryPunct(token: string): string {
|
|
154
|
+
return token.replace(/^[.,!?;:'"()[\]{}]+|[.,!?;:'"()[\]{}]+$/g, '');
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Clause/sentence punctuation at the token's end (closing quotes/brackets tolerated). */
|
|
158
|
+
function endsWithClausePunctuation(token: string): boolean {
|
|
159
|
+
const bare = token.replace(TRAILING_CLOSERS, '');
|
|
160
|
+
const last = bare.charAt(bare.length - 1);
|
|
161
|
+
if (!last) return false;
|
|
162
|
+
if (last === ',') {
|
|
163
|
+
// Digit-grouping commas never end a token (a trailing comma has no
|
|
164
|
+
// following digit), so any terminal comma is a real pause.
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
return last === '.' || last === ';' || last === ':' || last === '!' || last === '?';
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Clamp helper shared by the query functions. */
|
|
171
|
+
function clamp(value: number, min: number, max: number): number {
|
|
172
|
+
return value < min ? min : value > max ? max : value;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Expected cumulative syllables at a (fractional) word position —
|
|
177
|
+
* linear interpolation over the prefix sums.
|
|
178
|
+
*/
|
|
179
|
+
export function expectedSyllablesAt(script: NarrationScript, wordPos: number): number {
|
|
180
|
+
const n = script.tokens.length;
|
|
181
|
+
if (n === 0) return 0;
|
|
182
|
+
const pos = clamp(wordPos, 0, n);
|
|
183
|
+
const idx = Math.floor(pos);
|
|
184
|
+
if (idx >= n) return script.totalSyllables;
|
|
185
|
+
return script.cumulativeSyllables[idx] + (pos - idx) * script.tokens[idx].syllables;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Inverse of {@link expectedSyllablesAt}: the fractional word position at
|
|
190
|
+
* which the script reaches `syllables` cumulative syllables. Used by the
|
|
191
|
+
* pacing controller's hard resync.
|
|
192
|
+
*/
|
|
193
|
+
export function wordPosAtExpectedSyllables(script: NarrationScript, syllables: number): number {
|
|
194
|
+
const n = script.tokens.length;
|
|
195
|
+
if (n === 0) return 0;
|
|
196
|
+
const target = clamp(syllables, 0, script.totalSyllables);
|
|
197
|
+
// Binary search: last index with cumulativeSyllables[idx] <= target.
|
|
198
|
+
let lo = 0;
|
|
199
|
+
let hi = n;
|
|
200
|
+
while (lo < hi) {
|
|
201
|
+
const mid = (lo + hi + 1) >> 1;
|
|
202
|
+
if (script.cumulativeSyllables[mid] <= target) lo = mid;
|
|
203
|
+
else hi = mid - 1;
|
|
204
|
+
}
|
|
205
|
+
if (lo >= n) return n;
|
|
206
|
+
const within = target - script.cumulativeSyllables[lo];
|
|
207
|
+
const sylls = script.tokens[lo].syllables;
|
|
208
|
+
return lo + (sylls > 0 ? within / sylls : 0);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Index of the token containing (or following) a char offset into sourceText. */
|
|
212
|
+
export function wordIndexAtChar(script: NarrationScript, charOffset: number): number {
|
|
213
|
+
const tokens = script.tokens;
|
|
214
|
+
if (tokens.length === 0) return 0;
|
|
215
|
+
let lo = 0;
|
|
216
|
+
let hi = tokens.length - 1;
|
|
217
|
+
while (lo < hi) {
|
|
218
|
+
const mid = (lo + hi) >> 1;
|
|
219
|
+
if (tokens[mid].charEnd <= charOffset) lo = mid + 1;
|
|
220
|
+
else hi = mid;
|
|
221
|
+
}
|
|
222
|
+
return lo;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Index of the active word at a playback time, given aligned word
|
|
227
|
+
* timings — the last word whose `tSec` ≤ `tSec` (or 0 before the first).
|
|
228
|
+
*/
|
|
229
|
+
export function wordIndexAtTime(words: WordTiming[], tSec: number): number {
|
|
230
|
+
if (words.length === 0) return 0;
|
|
231
|
+
let lo = 0;
|
|
232
|
+
let hi = words.length - 1;
|
|
233
|
+
while (lo < hi) {
|
|
234
|
+
const mid = (lo + hi + 1) >> 1;
|
|
235
|
+
if (words[mid].tSec <= tSec) lo = mid;
|
|
236
|
+
else hi = mid - 1;
|
|
237
|
+
}
|
|
238
|
+
return words[lo].tSec <= tSec ? lo : 0;
|
|
239
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live-session composition: one pure call per PCM hop runs feature
|
|
3
|
+
* extraction → VAD → nuclei → pacing. This is the only surface the
|
|
4
|
+
* editor's mic loop needs — feed it worklet batches, read
|
|
5
|
+
* `state.pacing.wordPos` / `state.vad.speaking` / `state.lastFrame`.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { createFeatureState, featureStep, type FeatureState } from './features.js';
|
|
9
|
+
import { createNucleiState, nucleiStep, type NucleiState } from './nuclei.js';
|
|
10
|
+
import { createPacingState, pacingStep, reanchorPacing, type PacingState } from './pacing.js';
|
|
11
|
+
import { createVadState, vadStep, type VadState } from './vad.js';
|
|
12
|
+
import type {
|
|
13
|
+
FeatureConfig,
|
|
14
|
+
FrameFeatures,
|
|
15
|
+
NarrationScript,
|
|
16
|
+
NucleiConfig,
|
|
17
|
+
PacingConfig,
|
|
18
|
+
VadConfig,
|
|
19
|
+
} from './types.js';
|
|
20
|
+
|
|
21
|
+
export interface NarrationSessionConfig {
|
|
22
|
+
feature?: Partial<FeatureConfig>;
|
|
23
|
+
vad?: Partial<VadConfig>;
|
|
24
|
+
nuclei?: Partial<NucleiConfig>;
|
|
25
|
+
pacing?: Partial<PacingConfig>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface NarrationSessionState {
|
|
29
|
+
script: NarrationScript;
|
|
30
|
+
config: NarrationSessionConfig;
|
|
31
|
+
features: FeatureState;
|
|
32
|
+
vad: VadState;
|
|
33
|
+
nuclei: NucleiState;
|
|
34
|
+
pacing: PacingState;
|
|
35
|
+
/** Most recent analysis frame — drives the UI level meter. */
|
|
36
|
+
lastFrame: FrameFeatures | null;
|
|
37
|
+
/** Seconds of PCM consumed so far. */
|
|
38
|
+
tSec: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function createNarrationSession(
|
|
42
|
+
sampleRate: number,
|
|
43
|
+
script: NarrationScript,
|
|
44
|
+
config?: NarrationSessionConfig,
|
|
45
|
+
): NarrationSessionState {
|
|
46
|
+
const merged = config ?? {};
|
|
47
|
+
return {
|
|
48
|
+
script,
|
|
49
|
+
config: merged,
|
|
50
|
+
features: createFeatureState(sampleRate, merged.feature),
|
|
51
|
+
vad: createVadState(merged.vad),
|
|
52
|
+
nuclei: createNucleiState(merged.nuclei),
|
|
53
|
+
pacing: createPacingState(0),
|
|
54
|
+
lastFrame: null,
|
|
55
|
+
tSec: 0,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Feed one hop of mono PCM; every completed frame advances VAD/nuclei/pacing. */
|
|
60
|
+
export function narrationSessionStep(
|
|
61
|
+
state: NarrationSessionState,
|
|
62
|
+
hop: Float32Array,
|
|
63
|
+
): NarrationSessionState {
|
|
64
|
+
const { state: features, frames } = featureStep(state.features, hop);
|
|
65
|
+
let vad = state.vad;
|
|
66
|
+
let nuclei = state.nuclei;
|
|
67
|
+
let pacing = state.pacing;
|
|
68
|
+
let lastFrame = state.lastFrame;
|
|
69
|
+
|
|
70
|
+
for (const frame of frames) {
|
|
71
|
+
vad = vadStep(vad, frame, state.config.vad);
|
|
72
|
+
const nucleiResult = nucleiStep(nuclei, frame, vad.speaking, state.config.nuclei);
|
|
73
|
+
nuclei = nucleiResult.state;
|
|
74
|
+
pacing = pacingStep(
|
|
75
|
+
pacing,
|
|
76
|
+
{ tSec: frame.tSec, speaking: vad.speaking, onsets: nucleiResult.onset !== null ? 1 : 0 },
|
|
77
|
+
state.script,
|
|
78
|
+
state.config.pacing,
|
|
79
|
+
);
|
|
80
|
+
lastFrame = frame;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return {
|
|
84
|
+
...state,
|
|
85
|
+
features,
|
|
86
|
+
vad,
|
|
87
|
+
nuclei,
|
|
88
|
+
pacing,
|
|
89
|
+
lastFrame,
|
|
90
|
+
tSec: state.tSec + hop.length / state.features.sampleRate,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Manual nudge/scroll: re-anchor the pacing controller at a word position. */
|
|
95
|
+
export function reanchorSession(
|
|
96
|
+
state: NarrationSessionState,
|
|
97
|
+
wordPos: number,
|
|
98
|
+
): NarrationSessionState {
|
|
99
|
+
return { ...state, pacing: reanchorPacing(state.pacing, wordPos, state.script) };
|
|
100
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Narration timing sidecar v3 — the extended `<audio>.timing.json`.
|
|
3
|
+
*
|
|
4
|
+
* v1 (the recorder's original shape) is `{ sourceText, duration,
|
|
5
|
+
* bookmarks }` with bookmarks always empty. v3 fills the bookmarks with
|
|
6
|
+
* real per-word timings from the aligner and adds contiguous per-block
|
|
7
|
+
* ranges. `version: 2` is already taken by the consolidated root
|
|
8
|
+
* `timing.json` (`{ version: 2, sections }`), hence v3.
|
|
9
|
+
*
|
|
10
|
+
* Compatibility contract (tested in both directions): v3 is a strict
|
|
11
|
+
* superset of v1, so the legacy `parseTimingJson` gate (requires
|
|
12
|
+
* `sourceText` + `duration`, ignores unknown keys) keeps accepting v3
|
|
13
|
+
* files; {@link parseNarrationTimingJson} accepts v1 files and returns
|
|
14
|
+
* them with empty `blocks`.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { AudioBookmark } from '../schemas/Doc.js';
|
|
18
|
+
import type { NarrationAlignment, NarrationScript } from './types.js';
|
|
19
|
+
|
|
20
|
+
/** Narration time range of one doc block at record time. */
|
|
21
|
+
export interface NarrationTimingBlock {
|
|
22
|
+
/** Doc block id at record time (primary match key; ids can drift on heading edits). */
|
|
23
|
+
blockId?: string;
|
|
24
|
+
/** Block heading at record time (human-readable + fuzzy match key). */
|
|
25
|
+
heading?: string;
|
|
26
|
+
/** Index in renderable-block order at record time. */
|
|
27
|
+
blockIndex: number;
|
|
28
|
+
/** Char range into `sourceText` — the durable content key. */
|
|
29
|
+
charStart: number;
|
|
30
|
+
charEnd: number;
|
|
31
|
+
startSec: number;
|
|
32
|
+
/** Contiguous with the next block's startSec (aligner invariant). */
|
|
33
|
+
endSec: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface NarrationTimingJsonV3 {
|
|
37
|
+
version: 3;
|
|
38
|
+
/** EXACTLY the NarrationScript.sourceText of the take. */
|
|
39
|
+
sourceText: string;
|
|
40
|
+
/** Take length in seconds (decoded-PCM length, not the recorder clock). */
|
|
41
|
+
duration: number;
|
|
42
|
+
/** Per-word timings: { id: `word-${i}`, time, charOffset, textFragment }. */
|
|
43
|
+
bookmarks: AudioBookmark[];
|
|
44
|
+
blocks: NarrationTimingBlock[];
|
|
45
|
+
/** Start skew of the companion camera recording, when one exists. */
|
|
46
|
+
cameraOffsetSec?: number;
|
|
47
|
+
/** Provenance of the timing data. */
|
|
48
|
+
generator?: { name: string; method: 'dsp-align'; baseWpm?: number };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface BuildNarrationTimingOptions {
|
|
52
|
+
cameraOffsetSec?: number;
|
|
53
|
+
baseWpm?: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Build the v3 sidecar payload from a script + its alignment. Pure. */
|
|
57
|
+
export function buildNarrationTimingJson(
|
|
58
|
+
script: NarrationScript,
|
|
59
|
+
alignment: NarrationAlignment,
|
|
60
|
+
durationSec: number,
|
|
61
|
+
options?: BuildNarrationTimingOptions,
|
|
62
|
+
): NarrationTimingJsonV3 {
|
|
63
|
+
const bookmarks: AudioBookmark[] = alignment.words.map((word) => {
|
|
64
|
+
const token = script.tokens[word.tokenIndex];
|
|
65
|
+
return {
|
|
66
|
+
id: `word-${word.tokenIndex}`,
|
|
67
|
+
time: word.tSec,
|
|
68
|
+
charOffset: token?.charOffset ?? 0,
|
|
69
|
+
textFragment: token?.text ?? '',
|
|
70
|
+
};
|
|
71
|
+
});
|
|
72
|
+
const blocks: NarrationTimingBlock[] = alignment.blocks.map((range) => ({
|
|
73
|
+
...(range.blockId ? { blockId: range.blockId } : {}),
|
|
74
|
+
...(range.heading !== undefined ? { heading: range.heading } : {}),
|
|
75
|
+
blockIndex: range.blockIndex,
|
|
76
|
+
charStart: range.charStart,
|
|
77
|
+
charEnd: range.charEnd,
|
|
78
|
+
startSec: range.startSec,
|
|
79
|
+
endSec: range.endSec,
|
|
80
|
+
}));
|
|
81
|
+
return {
|
|
82
|
+
version: 3,
|
|
83
|
+
sourceText: script.sourceText,
|
|
84
|
+
duration: Number.isFinite(durationSec) && durationSec >= 0 ? durationSec : 0,
|
|
85
|
+
bookmarks,
|
|
86
|
+
blocks,
|
|
87
|
+
...(options?.cameraOffsetSec !== undefined ? { cameraOffsetSec: options.cameraOffsetSec } : {}),
|
|
88
|
+
generator: {
|
|
89
|
+
name: 'squisq-teleprompter',
|
|
90
|
+
method: 'dsp-align',
|
|
91
|
+
...(options?.baseWpm !== undefined ? { baseWpm: options.baseWpm } : {}),
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function finiteNonNegative(value: unknown): value is number {
|
|
97
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Tolerant parse: accepts v3, and v1 (`{ sourceText, duration,
|
|
102
|
+
* bookmarks? }`) which comes back with empty `blocks`. Returns null for
|
|
103
|
+
* malformed payloads. Blocks are sorted and clamped monotonic
|
|
104
|
+
* defensively (hand-edited sidecars).
|
|
105
|
+
*/
|
|
106
|
+
export function parseNarrationTimingJson(
|
|
107
|
+
data: ArrayBuffer | Uint8Array | string,
|
|
108
|
+
): NarrationTimingJsonV3 | null {
|
|
109
|
+
try {
|
|
110
|
+
const text =
|
|
111
|
+
typeof data === 'string'
|
|
112
|
+
? data
|
|
113
|
+
: new TextDecoder().decode(data instanceof Uint8Array ? data : new Uint8Array(data));
|
|
114
|
+
const parsed: unknown = JSON.parse(text);
|
|
115
|
+
if (typeof parsed !== 'object' || parsed === null) return null;
|
|
116
|
+
const raw = parsed as Record<string, unknown>;
|
|
117
|
+
if (typeof raw.sourceText !== 'string' || !finiteNonNegative(raw.duration)) return null;
|
|
118
|
+
|
|
119
|
+
const bookmarks: AudioBookmark[] = Array.isArray(raw.bookmarks)
|
|
120
|
+
? (raw.bookmarks as unknown[]).flatMap((b): AudioBookmark[] => {
|
|
121
|
+
if (typeof b !== 'object' || b === null) return [];
|
|
122
|
+
const bookmark = b as Record<string, unknown>;
|
|
123
|
+
if (!finiteNonNegative(bookmark.time) || !finiteNonNegative(bookmark.charOffset)) {
|
|
124
|
+
return [];
|
|
125
|
+
}
|
|
126
|
+
return [
|
|
127
|
+
{
|
|
128
|
+
id: typeof bookmark.id === 'string' ? bookmark.id : `bookmark-${bookmark.charOffset}`,
|
|
129
|
+
time: bookmark.time,
|
|
130
|
+
charOffset: bookmark.charOffset,
|
|
131
|
+
...(typeof bookmark.textFragment === 'string'
|
|
132
|
+
? { textFragment: bookmark.textFragment }
|
|
133
|
+
: {}),
|
|
134
|
+
},
|
|
135
|
+
];
|
|
136
|
+
})
|
|
137
|
+
: [];
|
|
138
|
+
|
|
139
|
+
let blocks: NarrationTimingBlock[] = Array.isArray(raw.blocks)
|
|
140
|
+
? (raw.blocks as unknown[]).flatMap((b): NarrationTimingBlock[] => {
|
|
141
|
+
if (typeof b !== 'object' || b === null) return [];
|
|
142
|
+
const block = b as Record<string, unknown>;
|
|
143
|
+
if (
|
|
144
|
+
!finiteNonNegative(block.startSec) ||
|
|
145
|
+
!finiteNonNegative(block.endSec) ||
|
|
146
|
+
!finiteNonNegative(block.charStart) ||
|
|
147
|
+
!finiteNonNegative(block.charEnd)
|
|
148
|
+
) {
|
|
149
|
+
return [];
|
|
150
|
+
}
|
|
151
|
+
return [
|
|
152
|
+
{
|
|
153
|
+
...(typeof block.blockId === 'string' ? { blockId: block.blockId } : {}),
|
|
154
|
+
...(typeof block.heading === 'string' ? { heading: block.heading } : {}),
|
|
155
|
+
blockIndex: finiteNonNegative(block.blockIndex) ? block.blockIndex : 0,
|
|
156
|
+
charStart: block.charStart,
|
|
157
|
+
charEnd: block.charEnd,
|
|
158
|
+
startSec: block.startSec,
|
|
159
|
+
endSec: Math.max(block.startSec, block.endSec),
|
|
160
|
+
},
|
|
161
|
+
];
|
|
162
|
+
})
|
|
163
|
+
: [];
|
|
164
|
+
|
|
165
|
+
blocks = blocks.sort((a, b) => a.startSec - b.startSec);
|
|
166
|
+
let cursor = 0;
|
|
167
|
+
for (const block of blocks) {
|
|
168
|
+
if (block.startSec < cursor) block.startSec = cursor;
|
|
169
|
+
if (block.endSec < block.startSec) block.endSec = block.startSec;
|
|
170
|
+
cursor = block.startSec;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return {
|
|
174
|
+
version: 3,
|
|
175
|
+
sourceText: raw.sourceText,
|
|
176
|
+
duration: raw.duration,
|
|
177
|
+
bookmarks,
|
|
178
|
+
blocks,
|
|
179
|
+
...(finiteNonNegative(raw.cameraOffsetSec) ? { cameraOffsetSec: raw.cameraOffsetSec } : {}),
|
|
180
|
+
...(typeof raw.generator === 'object' && raw.generator !== null
|
|
181
|
+
? { generator: raw.generator as NarrationTimingJsonV3['generator'] }
|
|
182
|
+
: {}),
|
|
183
|
+
};
|
|
184
|
+
} catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic English-oriented syllable estimation.
|
|
3
|
+
*
|
|
4
|
+
* Approximation limits (accepted by design): ±1 on roughly 15% of
|
|
5
|
+
* English words; systematically wrong on loanwords ("cafe", "naive"),
|
|
6
|
+
* some vowel-hiatus words ("create", "quiet"), and non-English text.
|
|
7
|
+
* Every consumer tolerates per-word error — the pacing controller
|
|
8
|
+
* smooths rates and anchors on cumulative sums, and the aligner pays
|
|
9
|
+
* symmetric insert/delete costs — so the estimator only needs to be
|
|
10
|
+
* unbiased on average. Exact outputs are part of the deterministic
|
|
11
|
+
* contract (tests pin a corpus table).
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { estimateSpokenWordCount } from '../timing/narrationTiming.js';
|
|
15
|
+
|
|
16
|
+
/** Same boundary-punctuation strip as `countSpokenWords`. */
|
|
17
|
+
const BOUNDARY_PUNCT = /^[.,!?;:'"()[\]{}]+|[.,!?;:'"()[\]{}]+$/g;
|
|
18
|
+
|
|
19
|
+
/** Average syllables per spoken word-equivalent when expanding numbers. */
|
|
20
|
+
const SYLLABLES_PER_SPOKEN_WORD = 1.4;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Estimate the syllable count of a single whitespace-delimited token.
|
|
24
|
+
* Always ≥ 1 for non-empty tokens.
|
|
25
|
+
*/
|
|
26
|
+
export function estimateSyllables(token: string): number {
|
|
27
|
+
const stripped = token.replace(BOUNDARY_PUNCT, '');
|
|
28
|
+
if (!stripped) return 1;
|
|
29
|
+
|
|
30
|
+
// Numeric tokens: expand via the spoken-word estimator ("1910" →
|
|
31
|
+
// "nineteen ten" ≈ 2 spoken words × 1.3 × 1.4 ≈ 4 syllables).
|
|
32
|
+
if (/^[-+]?[\d.,]+$/.test(stripped)) {
|
|
33
|
+
const num = parseFloat(stripped.replace(/,/g, ''));
|
|
34
|
+
if (!Number.isNaN(num) && Number.isFinite(num)) {
|
|
35
|
+
return Math.max(1, Math.round(estimateSpokenWordCount(stripped) * SYLLABLES_PER_SPOKEN_WORD));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Vowel-less all-caps runs read as initialisms letter by letter
|
|
40
|
+
// ("HTML" → aitch-tee-em-el ≈ 4). "NASA" has vowels and falls through.
|
|
41
|
+
if (/^[A-Z]{2,5}$/.test(stripped) && !/[AEIOUY]/.test(stripped)) {
|
|
42
|
+
return stripped.length;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Hyphenated/slashed compounds: sum the parts ("beam-splitter" → 3).
|
|
46
|
+
const parts = stripped
|
|
47
|
+
.toLowerCase()
|
|
48
|
+
.split(/[^a-z']+/)
|
|
49
|
+
.filter((p) => p.length > 0);
|
|
50
|
+
if (parts.length === 0) return 1;
|
|
51
|
+
let total = 0;
|
|
52
|
+
for (const part of parts) {
|
|
53
|
+
total += countAlphaSyllables(part.replace(/'/g, ''));
|
|
54
|
+
}
|
|
55
|
+
return Math.max(1, total);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Vowel-group heuristic over a lowercase alphabetic word. */
|
|
59
|
+
function countAlphaSyllables(word: string): number {
|
|
60
|
+
if (!word) return 0;
|
|
61
|
+
const groups = word.match(/[aeiouy]+/g);
|
|
62
|
+
let count = groups ? groups.length : 0;
|
|
63
|
+
if (count === 0) return 1;
|
|
64
|
+
|
|
65
|
+
if (count > 1 && /[^aeiouy]e$/.test(word)) {
|
|
66
|
+
// Terminal silent e: "table", "whale", "give".
|
|
67
|
+
count -= 1;
|
|
68
|
+
}
|
|
69
|
+
if (count > 1 && /[^aeiouy]ed$/.test(word) && !/[td]ed$/.test(word)) {
|
|
70
|
+
// Past-tense -ed is silent after most consonants ("walked"),
|
|
71
|
+
// syllabic after t/d ("wanted", "loaded").
|
|
72
|
+
count -= 1;
|
|
73
|
+
}
|
|
74
|
+
if (count > 1 && /[^aeiouy]es$/.test(word) && !/(?:[sxz]|[cs]h)es$/.test(word)) {
|
|
75
|
+
// Plural -es is silent after most consonants ("makes"), syllabic
|
|
76
|
+
// after sibilants ("boxes", "riches").
|
|
77
|
+
count -= 1;
|
|
78
|
+
}
|
|
79
|
+
if (/[^aeiouy]le$/.test(word)) {
|
|
80
|
+
// Syllabic -le after a consonant: "table", "little" — restores the
|
|
81
|
+
// syllable the silent-e rule removed. Vowel + "le" ("whale") skips.
|
|
82
|
+
count += 1;
|
|
83
|
+
}
|
|
84
|
+
return Math.max(1, count);
|
|
85
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live prompter trace: sparse `{ tMs, wordPos }` samples the UI records
|
|
3
|
+
* while the reader records a take (~4 Hz plus one on every re-anchor).
|
|
4
|
+
* The offline aligner uses it as a prior — a Sakoe-Chiba band around
|
|
5
|
+
* the trace keeps the DTW honest and cheap.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export interface TraceSample {
|
|
9
|
+
tMs: number;
|
|
10
|
+
wordPos: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface NarrationTrace {
|
|
14
|
+
samples: TraceSample[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Clamped linear interpolation of the trace at a time. */
|
|
18
|
+
export function traceWordPosAt(trace: NarrationTrace, tSec: number): number {
|
|
19
|
+
const samples = trace.samples;
|
|
20
|
+
if (samples.length === 0) return 0;
|
|
21
|
+
const tMs = tSec * 1000;
|
|
22
|
+
if (tMs <= samples[0].tMs) return samples[0].wordPos;
|
|
23
|
+
const last = samples[samples.length - 1];
|
|
24
|
+
if (tMs >= last.tMs) return last.wordPos;
|
|
25
|
+
// Binary search: last sample with tMs <= target.
|
|
26
|
+
let lo = 0;
|
|
27
|
+
let hi = samples.length - 1;
|
|
28
|
+
while (lo < hi) {
|
|
29
|
+
const mid = (lo + hi + 1) >> 1;
|
|
30
|
+
if (samples[mid].tMs <= tMs) lo = mid;
|
|
31
|
+
else hi = mid - 1;
|
|
32
|
+
}
|
|
33
|
+
const a = samples[lo];
|
|
34
|
+
const b = samples[lo + 1];
|
|
35
|
+
const span = b.tMs - a.tMs;
|
|
36
|
+
if (span <= 0) return a.wordPos;
|
|
37
|
+
return a.wordPos + ((tMs - a.tMs) / span) * (b.wordPos - a.wordPos);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Downsample to at most `maxSamples`, always keeping both endpoints. */
|
|
41
|
+
export function downsampleTrace(trace: NarrationTrace, maxSamples: number): NarrationTrace {
|
|
42
|
+
const samples = trace.samples;
|
|
43
|
+
if (maxSamples < 2 || samples.length <= maxSamples) return { samples: samples.slice() };
|
|
44
|
+
const out: TraceSample[] = [];
|
|
45
|
+
const stride = (samples.length - 1) / (maxSamples - 1);
|
|
46
|
+
for (let i = 0; i < maxSamples; i++) {
|
|
47
|
+
out.push(samples[Math.round(i * stride)]);
|
|
48
|
+
}
|
|
49
|
+
return { samples: out };
|
|
50
|
+
}
|