Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
fix(speech): preserve Chinese word timing through alignment and captions
kashorin87ac1a5b9223
diff --git a/packages/caption-fine/README.md b/packages/caption-fine/README.mdindex 65e741f0..585a32cc 100644--- a/packages/caption-fine/README.md+++ b/packages/caption-fine/README.md@@ -97,8 +97,23 @@ font fallbacks supply the required glyphs; the layout does not select a font byBoth count limits are omitted above so the example flows by available width. For a compactsingle-line treatment, author coherent Cues and choose a font, size and width that fit those Cues.`karaoke: off` keeps a complete Cue steady; `current` and `trail` follow its timed units, which are-normally individual characters in Chinese. The Hypit Skill's Caption craft page owns grouping and-visual direction.+normally individual characters in Chinese.++| Effect | Recipe | Visible behavior |+| --- | --- | --- |+| Whole-character emphasis | `karaoke: current; karaoke-transition: step` | The complete current unit takes the active Paint at its start, returning to base Paint at its end. |+| Accumulating emphasis | `karaoke: trail; karaoke-transition: step` | Each complete unit takes the active Paint at its start and keeps it for the rest of the Cue. |+| Sweeping fill | `karaoke: trail; karaoke-transition: wipe` | Paint sweeps inside each unit's glyphs during that unit's own time window. |+| Spoken-unit appearance | `atom-reveal: on-start` | Each complete unit appears at its start. |+| Typing appearance | `atom-reveal: typewriter` | Whole graphemes appear in sequence within each unit, starting with its first grapheme at the unit's start. A normal Han unit appears as a complete character. |++`step` is the default Karaoke transition. Choose it for ordinary Chinese character highlighting;+`wipe` deliberately produces partial glyph fills. Cue width and duration do not supply a substitute+clock for either mode. `atom-reveal` controls text appearing, independently of Karaoke recoloring+already visible text. A Dual Text span shares one timing unit, so its display words activate together+under `step`; keep pronunciation markup scoped to the name or expression that needs it.++The Hypit Skill's Caption craft page owns grouping and visual direction.`font` accepts an exact face or ordered stack. A local file declared through `media:Font` can be theprimary face or a `<caption-fine:Fallback font={...}/>` child, just like a bundled face. Seediff --git a/packages/caption-fine/src/manifest.ts b/packages/caption-fine/src/manifest.tsindex 72259364..68d994e4 100644--- a/packages/caption-fine/src/manifest.ts+++ b/packages/caption-fine/src/manifest.ts@@ -206,7 +206,7 @@ export const captionFineMarkupSurfaces = [{ name: "karaoke", required: false, values: ["off", "current", "trail"], fallback: "off",summary: "Decides whether the active Paint marks only the Word being spoken or every Word up to it." },{ name: "karaoke-transition", required: false, values: ["step", "wipe"], fallback: "step",- summary: "Decides whether the karaoke Paint snaps at the Word boundary or sweeps across the glyphs." },+ summary: "step activates each whole timed unit at its start (normally one Han character in Chinese); wipe sweeps inside that unit's glyphs during its own interval." },{ name: "active-box", required: false, values: ["off", "current", "trail"], fallback: "off",summary: "Decides whether a highlight box sits behind the Word being spoken or behind every Word up to it." },{ name: "active-box-continuity", required: false, values: ["isolated", "joined"], fallback: "isolated",diff --git a/packages/caption-fine/src/render.ts b/packages/caption-fine/src/render.tsindex eb4131af..6b330af8 100644--- a/packages/caption-fine/src/render.ts+++ b/packages/caption-fine/src/render.ts@@ -480,23 +480,6 @@ function karaokeWipeAnimation(] };}-function typewriterAnimation(- text: string,- parameters: FineCaptionParameters,- startFrame: number,- endFrame: number,- durationFrames: number,-): VisualAnimation | undefined {- if (parameters.motion.atomReveal !== "typewriter") return undefined;- const graphemes = Math.max(1, [...new Intl.Segmenter("und", { granularity: "grapheme" }).segment(text)].length);- const span = Math.max(1, endFrame - startFrame);- const offsets = Array.from({ length: graphemes + 1 }, (_, index) => startFrame + Math.round(span * index / graphemes));- return animationFrom(durationFrames, [...stepOffsets(startFrame), ...offsets], (frame) => {- const progress = frame < startFrame ? 0 : Math.floor(clamp((frame - startFrame) / span, 0, 1) * graphemes) / graphemes;- return [{ name: "clip-path", value: wipeClip(progress, parameters.layout.direction) }];- });-}-function activeResponseAnimation(parameters: FineCaptionParameters,startFrame: number,@@ -867,9 +850,7 @@ function cueElements(// the karaoke wipe keeps sitting on the letterforms it reveals.const gaps = wordGaps(surfaces);const wordGap = uniformGap(gaps);- const atomText = joinSurfaces(surfaces, " ");const entryId = `${atomId}-entry`;- const typewriterId = `${atomId}-typewriter`;const loopId = `${atomId}-loop`;const responseId = `${atomId}-response`;if (parameters.layout.maxWordsPerLine !== undefined@@ -884,7 +865,6 @@ function cueElements(wordsOnLine = 0;}const entryAnimation = atomLifecycleAnimation(parameters, timing.start, timing.end, durationFrames);- const writerAnimation = typewriterAnimation(atomText, parameters, timing.start, timing.end, durationFrames);const atomLoop = parameters.motion.loopTarget === "active-atom"? loopAnimation(parameters, durationFrames, activationTiming) : undefined;const responseAnimation = activeResponseAnimation(@@ -906,20 +886,9 @@ function cueElements(],...(entryAnimation === undefined ? {} : { animation: entryAnimation }),});- push({- id: typewriterId,- parent: entryId,- kind: "box",- style: [- { name: "display", value: "inline-flex" },- { name: "min-width", value: "0" },- { name: "transform-origin", value: parameters.layout.direction === "rtl" ? "right center" : "left center" },- ],- ...(writerAnimation === undefined ? {} : { animation: writerAnimation }),- });push({id: loopId,- parent: typewriterId,+ parent: entryId,kind: "box",style: [{ name: "display", value: "inline-flex" },@@ -983,10 +952,53 @@ function cueElements(attributes: [{ name: "data-caption-active-box", value: "isolated" }],});}+ const graphemes = parameters.motion.atomReveal === "typewriter"+ ? surfaces.map((text) =>+ [...new Intl.Segmenter("und", { granularity: "grapheme" }).segment(text)].map((part) => part.segment))+ : [];+ const graphemeCount = graphemes.reduce((sum, word) => sum + word.length, 0);+ const pushText = (element: Omit<VisualTextElement, "order">, wordIndex: number): void => {+ if (parameters.motion.atomReveal !== "typewriter") {+ push(element);+ return;+ }+ // Reveal complete glyphs, not fractions of a Word's width. Variable-width Latin letters,+ // Han characters and combining sequences all retain their actual layout widths.+ const isMargin = (name: string): boolean => name.startsWith("margin-");+ push({+ id: element.id,+ ...(element.parent === undefined ? {} : { parent: element.parent }),+ kind: "box",+ style: [+ { name: "display", value: "inline" },+ { name: "min-width", value: "0" },+ ...element.style.filter(({ name }) => isMargin(name) || name === "opacity"),+ ],+ ...(element.attributes === undefined ? {} : { attributes: element.attributes }),+ });+ const preceding = graphemes.slice(0, wordIndex).reduce((sum, word) => sum + word.length, 0);+ const { attributes: _attributes, ...glyph } = element;+ for (const [index, text] of (graphemes[wordIndex] ?? []).entries()) {+ const revealFrame = timing.start + Math.floor(+ (timing.end - timing.start) * (preceding + index) / Math.max(1, graphemeCount),+ );+ push({+ ...glyph,+ id: `${element.id}-grapheme-${index + 1}`,+ parent: element.id,+ text,+ style: [+ ...element.style.filter(({ name }) => !isMargin(name) && name !== "opacity"),+ { name: "display", value: "inline" },+ ],+ animation: activationStepAnimation("trail", revealFrame, durationFrames, durationFrames),+ });+ }+ };for (const [wordIndex, wordId] of atom.wordIds.entries()) {const text = wordText.get(wordId);if (text === undefined) throw new Error(`Fine Caption Atom references unknown word ${wordId}`);- push({+ pushText({id: `${atomId}-base-${wordIndex + 1}`,parent: atomId,kind: "text",@@ -997,7 +1009,7 @@ function cueElements(],...glyphPaintFields(parameters.basePaint),fonts,- });+ }, wordIndex);}const addActivatedTextLayer = (suffix: string,@@ -1026,7 +1038,7 @@ function cueElements(});for (const [wordIndex, wordId] of atom.wordIds.entries()) {const text = wordText.get(wordId)!;- push({+ pushText({id: `${activeId}-${wordIndex + 1}`,parent: activeId,kind: "text",@@ -1041,7 +1053,7 @@ function cueElements(...(kind === "glyph" ? glyphPaintFields(parameters.activePaint) : {}),fonts,attributes: [{ name: kind === "glyph" ? "data-caption-active-word" : "data-caption-underlined-word", value: wordId }],- });+ }, wordIndex);}};if (parameters.karaoke.mode !== "off") addActivatedTextLayer("active", parameters.karaoke.mode, "glyph");diff --git a/packages/caption-fine/test/caption-fine.test.ts b/packages/caption-fine/test/caption-fine.test.tsindex af5d227d..c2a331d1 100644--- a/packages/caption-fine/test/caption-fine.test.ts+++ b/packages/caption-fine/test/caption-fine.test.ts@@ -302,3 +302,99 @@ test("Fine Caption rejects token-specific Style runs instead of disguising a str/one uniform token rule/u,);});++function unevenChineseCaption(properties: SvsRecipe["properties"] = {}) {+ const { document, program, projection } = fixture("<line>你真好看</line>");+ const { "max-lines": _lines, "max-words-per-line": _words, ...flow } = recipe.properties;+ const style = fineCaptionStyle("plain", {+ ...recipe, properties: { ...flow, ...properties },+ }, [font]);+ const windows = [[10, 13], [13, 32], [36, 42], [42, 55]] as const;+ const timed: TimedCaptionProjection = {+ ...projection,+ cues: [{ ...projection.cues[0]!, endFrameExclusive: 55,+ units: document.units.map((unit, index) => ({ unitId: unit.id,+ startFrame: windows[index]![0], endFrameExclusive: windows[index]![1] })),+ }],+ };+ const styled = { ...program, styles: [style] };+ const track = renderFineCaption(scheduleFineCaption(timed, styled, document), styled, document,+ sealProgramSpace({ id: "test-space", durationSec: 3, frameRate: { numerator: 30, denominator: 1 } }));+ return { track, windows };+}++function numericStyleAt(element: import("@hypit/composition").VisualElement, frame: number, name: string): number {+ const frames = element.animation!.keyframes;+ const left = [...frames].reverse().find((item) => item.atFrame <= frame)!;+ const right = frames.find((item) => item.atFrame > frame) ?? left;+ const value = (item: typeof left) => Number(item.style.find((item) => item.name === name)!.value);+ return left === right ? value(left)+ : value(left) + (value(right) - value(left)) * (frame - left.atFrame) / (right.atFrame - left.atFrame);+}++for (const mode of ["current", "trail"] as const) {+ test(`Chinese ${mode} karaoke, underline and boxes follow unequal character times and pauses`, () => {+ const { track, windows } = unevenChineseCaption({+ karaoke: mode, "active-underline": mode, "active-box": mode,+ });+ const present = track.presents[0]!;+ for (const [index, [start, end]] of windows.entries()) {+ for (const suffix of ["active", "underline", "box"]) {+ const element = present.elements.find((item) => item.id === `atom-${index + 1}-${suffix}`)!;+ assert.ok(element);+ for (let frame = present.span.startFrame; frame < present.span.endFrameExclusive; frame++) {+ const active = frame >= start && (mode === "trail" || frame < end);+ assert.equal(numericStyleAt(element, frame - present.span.startFrame, "opacity"), Number(active),+ `${suffix} character ${index + 1} at frame ${frame}`);+ }+ assert.equal(element.animation!.keyframes.some((keyframe) =>+ keyframe.style.some(({ name }) => name === "clip-path")), false);+ }+ }+ assert.equal(present.elements.find((item) => item.id === "cue")!.style+ .some(({ name }) => name === "column-gap"), false);+ });+}++test("Chinese wipe remains an explicit within-character effect with each character's own interval", () => {+ const { track, windows } = unevenChineseCaption({ karaoke: "trail", "karaoke-transition": "wipe" });+ const present = track.presents[0]!;+ for (const [index, [start, end]] of windows.entries()) {+ const active = present.elements.find((item) => item.id === `atom-${index + 1}-active`)!;+ const clip = (frame: number) => active.animation!.keyframes+ .find((item) => item.atFrame === frame - present.span.startFrame)!.style[0]!.value;+ assert.equal(clip(start), "inset(0 100% 0 0)");+ assert.equal(clip(end), "inset(0 0% 0 0)");+ }+});++test("Chinese typewriter reveals whole characters at their own starts, including uneven holds", () => {+ const { track, windows } = unevenChineseCaption({ "atom-reveal": "typewriter", karaoke: "trail" });+ const present = track.presents[0]!;+ for (const [index, [start]] of windows.entries()) {+ for (const layer of ["base", "active"]) {+ const glyph = present.elements.find((item) => item.id === `atom-${index + 1}-${layer}-1-grapheme-1`)!;+ assert.ok(glyph);+ for (let frame = present.span.startFrame; frame < present.span.endFrameExclusive; frame++) {+ assert.equal(numericStyleAt(glyph, frame - present.span.startFrame, "opacity"), Number(frame >= start));+ }+ }+ }+ assert.equal(present.elements.some((element) => element.animation?.keyframes.some((keyframe) =>+ keyframe.style.some(({ name }) => name === "clip-path"))), false);+});++test("Typewriter keeps combining graphemes whole and preserves unequal-width Latin letters", () => {+ const { document, program, projection } = fixture("<line>Wi e\u0301 || 繁體</line>");+ const style = fineCaptionStyle("plain", { ...recipe,+ properties: { ...recipe.properties, "atom-reveal": "typewriter" } }, [font]);+ const styled = { ...program, styles: [style] };+ const track = renderFineCaption(scheduleFineCaption(projection, styled, document), styled, document,+ sealProgramSpace({ id: "test-space", durationSec: 3, frameRate: { numerator: 30, denominator: 1 } }));+ const text = track.presents[0]!.elements.filter((element) => element.kind === "text");+ assert.deepEqual(text.map((element) => element.text), ["W", "i", "e\u0301"]);+ assert.equal(numericStyleAt(text[0]!, 4, "opacity"), 1);+ assert.equal(numericStyleAt(text[1]!, 8, "opacity"), 0);+ assert.equal(numericStyleAt(text[1]!, 9, "opacity"), 1);+ assert.equal(numericStyleAt(text[2]!, 14, "opacity"), 1);+});diff --git a/packages/caption/test/chinese-pipeline.test.ts b/packages/caption/test/chinese-pipeline.test.tsnew file mode 100644index 00000000..baca93a2--- /dev/null+++ b/packages/caption/test/chinese-pipeline.test.ts@@ -0,0 +1,71 @@+import assert from "node:assert/strict";+import test from "node:test";+import type { Narrative } from "@hypit/narrative";+import { captionDocument, narrativeValue, parseScript } from "@hypit/script";+import { alignSemanticTake } from "../../speech-alignment/src/index.js";+import { interpretWhisperXTranscript } from "../../whisperx/src/index.js";+import { appendSpeechTrackTake, assembleSpeechTrack, createSpeechTrackSet, sealSpeechTrackHeader } from "../../speech-track/src/index.js";+import { selectionFrameSpan } from "@hypit/semantic-track";+import { temporalizeCaptionDocument } from "../src/index.js";+import type { CaptionProgram } from "../src/index.js";+import { fixtureResource } from "../../../test/fixture-resource.js";++test("Chinese Script, WhisperX response, semantic assembly and captions preserve words, cue breaks and timing", () => {+ const parsed = parseScript("mixed-zh.svml", `<opening><HOST>用@brand ElevenLabs @/brand做视频,|| 真方便。</opening>+<answer><GUEST>今年<2026|二零二六>年,這個很好。</answer>`);+ const narrative = narrativeValue(parsed, "story") as unknown as Narrative;+ const document = captionDocument(parsed, "story.caption", "story");+ // Representative WhisperX zh wire output: Han characters and Latin letters carry separate times.+ // These fixtures test transport and mapping, not acoustic recognition accuracy.+ const phrases = ["用ElevenLabs做视频真方便", "今年二零二六年这个很好"];+ const durations = [4000, 3000];+ let set = createSpeechTrackSet();+ const evidenceWindows: Array<Array<[number, number]>> = [];+ for (const [index, segment] of narrative.segments.entries()) {+ let cursor = 100;+ const words = [...phrases[index]!].map((word, i) => {+ const start = cursor;+ cursor += i % 3 === 0 ? 190 : 90;+ const end = cursor;+ cursor += i % 4 === 0 ? 80 : 20;+ return { word, start: start / 1000, end: end / 1000 };+ });+ evidenceWindows.push(words.map(word => [Math.round(word.start * 1000), Math.round(word.end * 1000)]));+ const sampleFrames = durations[index]! * 16;+ const take = alignSemanticTake(narrative, {+ narrativeId: narrative.id, kind: "segment", id: segment.id,+ tokenStart: segment.tokenStart, tokenEndExclusive: segment.tokenEndExclusive,+ }, {+ timeline: { frameRate: { numerator: 1000, denominator: 1 }, frameCount: durations[index]! },+ audio: { artifact: { kind: "blob", resource: fixtureResource(`zh:${index}`), size: 1, mediaType: "audio/wav" } },+ }, { passages: interpretWhisperXTranscript({ language: "zh", segments: [{ start: 0,+ end: durations[index]! / 1000, words }] }, sampleFrames) });+ set = appendSpeechTrackTake(set, take);+ }+ const semantic = assembleSpeechTrack(sealSpeechTrackHeader({ id: "speech" }), set);+ const program: CaptionProgram = {+ id: "captions", documentId: document.id,+ styles: [{ id: "plain", rendering: { family: "test-caption@1", parameters: {} } }],+ runs: [{ id: "all", styleId: "plain", unitIds: document.units.map(unit => unit.id) }],+ wordRuns: [], mutedUnitIds: [],+ };+ const projection = temporalizeCaptionDocument(document, semantic, program);+ const wordText = new Map(document.words.map(word => [word.id, word.text]));+ const unitText = new Map(document.units.map(unit => [unit.id, unit.wordIds.map(id => wordText.get(id)!).join("")]));+ assert.deepEqual(projection.cues.map(cue => cue.units.map(unit => unitText.get(unit.unitId)).join("")),+ ["用ElevenLabs做视频,", "真方便。", "今年2026年,這個很好。"]);+ const units = projection.cues.flatMap(cue => cue.units);+ const windowsFor = (text: string) => units.filter(unit => unitText.get(unit.unitId) === text)+ .map(unit => [unit.startFrame, unit.endFrameExclusive]);+ const first = evidenceWindows[0]!;+ assert.deepEqual(windowsFor("用"), [first[0]]);+ assert.deepEqual(windowsFor("ElevenLabs"), [[first[1]![0], first[10]![1]]]);+ assert.deepEqual(windowsFor("做"), [first[11]]);+ const span = selectionFrameSpan(semantic, { ...narrative.selections[0]!, narrativeId: narrative.id });+ assert.deepEqual(span, { startFrame: first[1]![0], endFrameExclusive: first[10]![1] });+ const second = evidenceWindows[1]!;+ assert.deepEqual(windowsFor("2026"), [[4000 + second[2]![0], 4000 + second[5]![1]]]);+ assert.deepEqual(windowsFor("這"), [[4000 + second[7]![0], 4000 + second[7]![1]]]);+ assert.deepEqual(windowsFor("個"), [[4000 + second[8]![0], 4000 + second[8]![1]]]);+ assert.equal(document.units[0]!.role, "HOST");+});diff --git a/packages/speech-alignment/src/align.ts b/packages/speech-alignment/src/align.tsindex c8a1319d..cfdbf3b7 100644--- a/packages/speech-alignment/src/align.ts+++ b/packages/speech-alignment/src/align.ts@@ -66,6 +66,9 @@ function pairedCost(): number {const sourceText = comparisonText(source);const evidenceText = comparisonText(evidence);+ // Identical wording with different token boundaries is a segmentation difference. Its cost+ // must not grow with the number of letters a recognizer happens to emit for one word.+ if (sourceText === evidenceText) return source.length === 1 && evidence.length === 1 ? 0 : 0.055;const width = Math.max([...sourceText].length, [...evidenceText].length, 1);const distance = editDistance([...sourceText], [...evidenceText]) / width;const grouping = 0.055 * Math.max(0, source.length + evidence.length - 2);@@ -74,6 +77,17 @@ function pairedCost(return distance * evidenceReliability(evidence) + grouping + 0.06 * unmatchedWordBoundaries;}+function exactRunLength(target: string, parts: readonly string[], start: number): number {+ if (target.length === 0) return 0;+ let joined = "";+ for (let index = start; index < parts.length; index += 1) {+ joined += parts[index];+ if (joined === target) return index - start + 1;+ if (!target.startsWith(joined)) return 0;+ }+ return 0;+}+function better(candidate: Cell, current: Cell | undefined): boolean {if (!current) return true;if (candidate.cost < current.cost - EPSILON) return true;@@ -155,34 +169,44 @@ export function alignWordGroups(}};+ const sourceTexts = source.map((token) => normalizeForAlignment(token.text));+ const evidenceTexts = evidence.map((word) => normalizeForAlignment(word.text));for (let sourceIndex = 0; sourceIndex <= source.length; sourceIndex += 1) {for (let evidenceIndex = 0; evidenceIndex <= evidence.length; evidenceIndex += 1) {if (!rows[sourceIndex]![evidenceIndex]) continue;+ const pair = (sourceCount: number, evidenceCount: number): void => {+ const sourceGroup = source.slice(sourceIndex, sourceIndex + sourceCount);+ const evidenceGroup = evidence.slice(evidenceIndex, evidenceIndex + evidenceCount);+ const exactOneToOne = sourceCount === 1+ && evidenceCount === 1+ && sourceGroup[0]!.normalized === normalizeForAlignment(evidenceGroup[0]!.text);+ const cost = pairedCost(sourceGroup, evidenceGroup);+ update(+ sourceIndex,+ evidenceIndex,+ sourceIndex + sourceCount,+ evidenceIndex + evidenceCount,+ {+ sourceSegmentId,+ sourceTokenIds: sourceGroup.map((token) => token.id),+ evidenceWordStart: evidenceIndex,+ evidenceWordEndExclusive: evidenceIndex + evidenceCount,+ relation: relation(sourceCount, evidenceCount, exactOneToOne),+ cost,+ },+ exactOneToOne ? 1 : 0,+ );+ };for (let sourceCount = 1; sourceCount <= maxGroupSize && sourceIndex + sourceCount <= source.length; sourceCount += 1) {for (let evidenceCount = 1; evidenceCount <= maxGroupSize && evidenceIndex + evidenceCount <= evidence.length; evidenceCount += 1) {- const sourceGroup = source.slice(sourceIndex, sourceIndex + sourceCount);- const evidenceGroup = evidence.slice(evidenceIndex, evidenceIndex + evidenceCount);- const exactOneToOne = sourceCount === 1- && evidenceCount === 1- && sourceGroup[0]!.normalized === normalizeForAlignment(evidenceGroup[0]!.text);- const cost = pairedCost(sourceGroup, evidenceGroup);- update(- sourceIndex,- evidenceIndex,- sourceIndex + sourceCount,- evidenceIndex + evidenceCount,- {- sourceSegmentId,- sourceTokenIds: sourceGroup.map((token) => token.id),- evidenceWordStart: evidenceIndex,- evidenceWordEndExclusive: evidenceIndex + evidenceCount,- relation: relation(sourceCount, evidenceCount, exactOneToOne),- cost,- },- exactOneToOne ? 1 : 0,- );+ pair(sourceCount, evidenceCount);}}+ // Bound fuzzy alternatives, but follow a complete exact split/merge regardless of token count.+ const evidenceRun = exactRunLength(sourceTexts[sourceIndex] ?? "", evidenceTexts, evidenceIndex);+ if (evidenceRun > maxGroupSize) pair(1, evidenceRun);+ const sourceRun = exactRunLength(evidenceTexts[evidenceIndex] ?? "", sourceTexts, sourceIndex);+ if (sourceRun > maxGroupSize) pair(sourceRun, 1);if (sourceIndex < source.length) {const token = source[sourceIndex]!;update(diff --git a/packages/speech-alignment/test/speech-align.test.ts b/packages/speech-alignment/test/speech-align.test.tsindex 50352c62..ebdab091 100644--- a/packages/speech-alignment/test/speech-align.test.ts+++ b/packages/speech-alignment/test/speech-align.test.ts@@ -403,3 +403,23 @@ test("a backwards character measurement is treated as missing token timing", ()const middle = map.tokens[1]!;assert.equal(middle.endFrameExclusive > middle.startFrame, true);});++test("exact segmentation differences have no word-count ceiling", () => {+ const name = "ElevenLabs";+ const split = parseScript("letters.svml", `<line>用${name}做视频</line>`);+ const letters = [...`用${name}做视频`].map((text, index) => ({+ text, startSec: (100 + index * 200) / 1000, endSec: (200 + index * 200) / 1000,+ }));+ const map = locate(split, { words: letters, durationSec: 4 });+ assert.deepEqual(map.tokens.slice(0, 3).map((token, index) => [split.tokens[index]!.text, token.startFrame, token.endFrameExclusive]),+ [["用", 100, 200], [name, 300, 2200], ["做", 2300, 2400]]);++ const merged = parseScript("merged-zh.svml", "<line>这是非常自然的节奏</line>");+ const text = "这是非常自然的节奏";+ const starts = [...text].map((_, index) => (100 + index * 150) / 1000);+ const ends = starts.map(start => start + 0.08);+ const mergedMap = locate(merged, { words: [{ text, startSec: starts[0]!, endSec: ends.at(-1)! }],+ chars: characters(text, starts, ends), durationSec: 3 });+ assert.deepEqual(mergedMap.tokens.map(token => [token.startFrame, token.endFrameExclusive]),+ starts.map((start, index) => [Math.round(start * 1000), Math.round(ends[index]! * 1000)]));+});diff --git a/packages/whisperx/README.md b/packages/whisperx/README.mdindex b1c2cbf5..8e8c767f 100644--- a/packages/whisperx/README.md+++ b/packages/whisperx/README.md@@ -17,6 +17,13 @@ projects the Take's audio to canonical 16 kHz mono `SpeechEvidenceAudio`; Whispebytes. A deterministic local alignment then combines the returned evidence with the Segment andemits one self-contained `SemanticTake`.+For Chinese speech, select `zh` (also `hypit transcribe --language zh` for a reference). WhisperX's+Chinese alignment emits character-sized words, including letters inside some Latin names. The+evidence adapter preserves those windows; the local alignment maps them onto Script's units, so+a complete Latin name can consume several evidence words while neighboring Han characters retain+their own times. Caption gets its displayed wording and Cue breaks from Script, independently of+the recognizer's punctuation or simplified/traditional spelling.+When the authored Segment has no Tokens, write the same Surface without `language`. Its start andend Anchors map directly to the prepared media's first and final frame. There are no words to align,so this branch requests no evidence audio and no WhisperX capability:diff --git a/skills/hypit/references/playbooks/craft/captions.md b/skills/hypit/references/playbooks/craft/captions.mdindex e5db8eee..a9dfa9b2 100644--- a/skills/hypit/references/playbooks/craft/captions.md+++ b/skills/hypit/references/playbooks/craft/captions.md@@ -131,6 +131,18 @@ The same timing supports a stable complete Cue, current-character color or a traChinese speech, a readable phrase with restrained emphasis often works better than a separate bounceor reveal on every character. Choose the response for the performance's energy.+For whole-character highlighting, use `karaoke: current` with `karaoke-transition: step`.+Choose `trail` instead of `current` when the already spoken characters should stay highlighted.+`step` activates the complete timed unit at its start; `wipe` is a different visual choice that+sweeps inside its glyphs. Both follow each unit's own speech time, including uneven delivery and+pauses. Making a Cue longer changes its reading group, not its character timing.++Text appearing and text changing color are separate choices. `atom-reveal: all` keeps the complete+Cue available to read while Karaoke supplies emphasis; `on-start` reveals whole spoken units, and+`typewriter` reveals whole graphemes within them. A pronunciation span such as `<Hypit|Hai-Pit>`+remains one shared timing unit. Scope it to the expression needing a pronunciation hint so the+surrounding Chinese characters retain their own timing.+With Fine's uniform-flow family, direct the common Cue to remain on one line by considering itsgrouping together with the Recipe's font size, usable width and word gap. A stable line lets eachhandoff replace one readable block without repeatedly changing the block's height and the viewer'sdiff --git a/skills/hypit/references/production/caption-authoring.md b/skills/hypit/references/production/caption-authoring.mdindex 6c9fb1c6..d8d546f9 100644--- a/skills/hypit/references/production/caption-authoring.md+++ b/skills/hypit/references/production/caption-authoring.md@@ -97,6 +97,12 @@ grouping. Compose adjacent Han characters without Latin word gaps, preserve puncword, and use the selected fonts' actual widths for layout. Exercise mixed-script names as well asplain English when the family will carry Chinese copy.+For speech-following emphasis, activate each complete unit from its projected start and end.+A Cue-wide left-to-right progress bar follows elapsed time and text width, which is a different+effect from following spoken characters. Keep within-glyph wiping an explicit visual choice.+Use uneven unit durations and a pause in a short example to check that the chosen effect follows+the intended clock.+`caption:Mute` suppresses selected display units while preserving speech. A new family should usethe common mute application when scheduling, as Fine does. Validate that schedule, document, narrativeand ProgramSpace belong together; do not silently accept timing from another video.