Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): add edit transcript model and remapping helpers

Richie McIlroya4be5e43fa22
diff --git a/apps/web/__tests__/unit/edit-transcript.test.ts b/apps/web/__tests__/unit/edit-transcript.test.ts
new file mode 100644
index 000000000..d82d32940
--- /dev/null
+++ b/apps/web/__tests__/unit/edit-transcript.test.ts
@@ -0,0 +1,550 @@
+import type { VideoEditSpec } from "@cap/database/types";
+import { describe, expect, it } from "vitest";
+import {
+ createEditTranscript,
+ editTranscriptWordsToCaptionVtt,
+ findActiveTranscriptWordIndex,
+ getDeletedTranscriptWordIds,
+ groupEditTranscriptWords,
+ isFillerWord,
+ normalizeTranscriptSelection,
+ parseEditTranscript,
+ planFillerCuts,
+ planTranscriptCut,
+ remapEditTranscriptThroughSpec,
+ serializeEditTranscript,
+} from "@/lib/edit-transcript";
+import { createIdentityEditSpec } from "@/lib/video-edits";
+import {
+ assemblyAIEditResponse,
+ assemblyAIRealFillerResponse,
+} from "../fixtures/assemblyai-edit-response";
+
+function editSpec(
+ sourceDuration: number,
+ keepRanges: { start: number; end: number }[],
+): VideoEditSpec {
+ return { version: 1, sourceDuration, keepRanges };
+}
+
+describe("edit transcript", () => {
+ it("normalizes and preserves AssemblyAI word timing", () => {
+ const transcript = createEditTranscript(assemblyAIEditResponse, 4_000);
+
+ expect(transcript).toMatchObject({
+ version: 3,
+ speechModelUsed: "universal-3-5-pro",
+ durationMs: 4_000,
+ languageCode: "en",
+ });
+ expect(transcript.words).toHaveLength(9);
+ expect(transcript.words[0]).toMatchObject({
+ id: "word-0-120-380",
+ text: "Um,",
+ startMs: 120,
+ endMs: 380,
+ confidence: 0.98,
+ speaker: "A",
+ channel: null,
+ });
+ expect(parseEditTranscript(serializeEditTranscript(transcript))).toEqual(
+ transcript,
+ );
+ });
+
+ it("sorts, clamps, and rejects malformed provider words", () => {
+ const transcript = createEditTranscript(
+ {
+ speech_model_used: "universal-2",
+ words: [
+ { text: "second", start: 800, end: 900 },
+ { text: "first", start: -100, end: 250, confidence: 2 },
+ { text: "", start: 300, end: 400 },
+ { text: "invalid", start: Number.NaN, end: 600 },
+ { text: "reverse", start: 700, end: 650, channel: 1 },
+ { text: "outside", start: 1_100, end: 1_200 },
+ ],
+ language_code: null,
+ },
+ 1_000,
+ );
+
+ expect(transcript.words.map((word) => word.text)).toEqual([
+ "first",
+ "reverse",
+ "second",
+ ]);
+ expect(transcript.words[0]?.confidence).toBe(1);
+ expect(transcript.words[1]?.channel).toBe("1");
+ });
+
+ it("records whichever speech model the provider used", () => {
+ expect(
+ createEditTranscript(
+ { ...assemblyAIEditResponse, speech_model_used: "universal-2" },
+ 4_000,
+ ).speechModelUsed,
+ ).toBe("universal-2");
+ expect(
+ createEditTranscript(
+ { ...assemblyAIEditResponse, speech_model_used: undefined },
+ 4_000,
+ ).speechModelUsed,
+ ).toBe("unknown");
+ });
+
+ it("preserves fillers from the real accuracy regression response", () => {
+ const transcript = createEditTranscript(
+ assemblyAIRealFillerResponse,
+ 8_000,
+ );
+
+ expect(
+ transcript.words
+ .filter((word) => isFillerWord(word.text))
+ .map(({ text, startMs, endMs, confidence }) => ({
+ text,
+ startMs,
+ endMs,
+ confidence,
+ })),
+ ).toEqual([
+ {
+ text: "um,",
+ startMs: 3_460,
+ endMs: 3_980,
+ confidence: 0.9959265,
+ },
+ {
+ text: "Uh,",
+ startMs: 5_760,
+ endMs: 7_240,
+ confidence: 0.9857637,
+ },
+ ]);
+ });
+
+ it("recognizes exact filler variants without substring false positives", () => {
+ for (const filler of [
+ "um",
+ "Umm,",
+ "uh",
+ "uhhh!",
+ "erm",
+ "ermm",
+ "er",
+ "ah",
+ "ahh",
+ "hmm",
+ ]) {
+ expect(isFillerWord(filler), filler).toBe(true);
+ }
+
+ for (const word of [
+ "umbrella",
+ "term",
+ "human",
+ "ahead",
+ "hammer",
+ "m",
+ "mhm",
+ "huh",
+ "uh-huh",
+ ]) {
+ expect(isFillerWord(word), word).toBe(false);
+ }
+ });
+
+ it("normalizes forward and backward word selections", () => {
+ expect(normalizeTranscriptSelection(2, 5, 8)).toEqual({
+ startIndex: 2,
+ endIndex: 5,
+ });
+ expect(normalizeTranscriptSelection(5, 2, 8)).toEqual({
+ startIndex: 2,
+ endIndex: 5,
+ });
+ expect(normalizeTranscriptSelection(-1, 2, 8)).toBeNull();
+ expect(normalizeTranscriptSelection(2, 8, 8)).toBeNull();
+ });
+
+ it("uses bounded silence padding for a selected word", () => {
+ const transcript = createEditTranscript(assemblyAIEditResponse, 4_000);
+ const plan = planTranscriptCut(transcript.words, 6, 6, 4_000);
+
+ expect(plan).toEqual({
+ startMs: 2_220,
+ endMs: 2_635,
+ safe: true,
+ reason: null,
+ });
+ });
+
+ it("marks a cut unsafe when unselected speech overlaps it", () => {
+ const transcript = createEditTranscript(
+ {
+ speech_model_used: "universal-2",
+ words: [
+ { text: "speaker one", start: 100, end: 500, speaker: "A" },
+ { text: "um", start: 200, end: 350, speaker: "B" },
+ { text: "continues", start: 520, end: 800, speaker: "A" },
+ ],
+ },
+ 1_000,
+ );
+
+ expect(planTranscriptCut(transcript.words, 1, 1, 1_000)).toEqual({
+ startMs: 200,
+ endMs: 350,
+ safe: false,
+ reason: "overlapping-speech",
+ });
+ expect(planFillerCuts(transcript.words, 1_000)).toEqual({
+ ranges: [],
+ fillerCount: 1,
+ skippedCount: 1,
+ });
+ });
+
+ it("plans batch filler cuts in chronological order", () => {
+ const transcript = createEditTranscript(assemblyAIEditResponse, 4_000);
+ const plan = planFillerCuts(transcript.words, 4_000);
+
+ expect(plan).toEqual({
+ ranges: [
+ {
+ startMs: 60,
+ endMs: 450,
+ safe: true,
+ reason: null,
+ },
+ {
+ startMs: 2_220,
+ endMs: 2_635,
+ safe: true,
+ reason: null,
+ },
+ ],
+ fillerCount: 2,
+ skippedCount: 0,
+ });
+ });
+
+ it("plans exact safe cuts for the real missing-filler response", () => {
+ const transcript = createEditTranscript(
+ assemblyAIRealFillerResponse,
+ 8_000,
+ );
+
+ expect(planFillerCuts(transcript.words, transcript.durationMs)).toEqual({
+ ranges: [
+ {
+ startMs: 3_380,
+ endMs: 3_980,
+ safe: true,
+ reason: null,
+ },
+ {
+ startMs: 5_760,
+ endMs: 7_240,
+ safe: true,
+ reason: null,
+ },
+ ],
+ fillerCount: 2,
+ skippedCount: 0,
+ });
+ });
+
+ it("groups words linearly and finds the active word with binary search", () => {
+ const transcript = createEditTranscript(assemblyAIEditResponse, 4_000);
+ const groups = groupEditTranscriptWords(transcript.words, 4);
+
+ expect(groups.map((group) => [group.startIndex, group.endIndex])).toEqual([
+ [0, 3],
+ [4, 5],
+ [6, 8],
+ ]);
+ expect(findActiveTranscriptWordIndex(transcript.words, 750)).toBe(2);
+ expect(findActiveTranscriptWordIndex(transcript.words, 2_000)).toBe(-1);
+ });
+
+ it("finds an earlier active speaker beneath completed overlapping words", () => {
+ const transcript = createEditTranscript(
+ {
+ speech_model_used: "universal-2",
+ words: [
+ { text: "long", start: 0, end: 1_000, speaker: "A" },
+ { text: "short", start: 100, end: 200, speaker: "B" },
+ { text: "later", start: 300, end: 400, speaker: "B" },
+ ],
+ },
+ 1_200,
+ );
+
+ expect(findActiveTranscriptWordIndex(transcript.words, 500)).toBe(0);
+ });
+
+ it("derives deleted word presentation from timeline keep ranges", () => {
+ const transcript = createEditTranscript(assemblyAIEditResponse, 4_000);
+ const deleted = getDeletedTranscriptWordIds(transcript.words, [
+ { start: 0.45, end: 2.22 },
+ { start: 2.635, end: 4 },
+ ]);
+
+ expect([...deleted]).toEqual(["word-0-120-380", "word-6-2300-2570"]);
+ });
+
+ it("handles a 50,000 word transcript without quadratic grouping", () => {
+ const transcript = createEditTranscript(
+ {
+ speech_model_used: "universal-2",
+ words: Array.from({ length: 50_000 }, (_, index) => ({
+ text: index % 100 === 0 ? "um" : `word${index}`,
+ start: index * 300,
+ end: index * 300 + 200,
+ })),
+ },
+ 15_000_000,
+ );
+
+ expect(groupEditTranscriptWords(transcript.words)).toHaveLength(1_042);
+ expect(
+ planFillerCuts(transcript.words, transcript.durationMs).fillerCount,
+ ).toBe(500);
+ expect(findActiveTranscriptWordIndex(transcript.words, 14_999_900)).toBe(
+ 49_999,
+ );
+ });
+
+ it("rejects malformed stored sidecars", () => {
+ expect(parseEditTranscript("not json")).toBeNull();
+ expect(
+ parseEditTranscript(
+ JSON.stringify({
+ version: 3,
+ speechModelUsed: "universal-3-5-pro",
+ durationMs: 1000,
+ languageCode: "en",
+ words: [{ id: "bad", text: "bad", startMs: 900, endMs: 1100 }],
+ }),
+ ),
+ ).toBeNull();
+ expect(
+ parseEditTranscript(
+ JSON.stringify({
+ version: 3,
+ speechModelUsed: "",
+ durationMs: 1000,
+ languageCode: "en",
+ words: [],
+ }),
+ ),
+ ).toBeNull();
+ });
+
+ it("rejects sidecars from previous schema versions and accepts any model", () => {
+ for (const version of [1, 2]) {
+ expect(
+ parseEditTranscript(
+ JSON.stringify({
+ version,
+ speechModelUsed: "universal-2",
+ durationMs: 1000,
+ languageCode: "en",
+ words: [],
+ }),
+ ),
+ ).toBeNull();
+ }
+
+ expect(
+ parseEditTranscript(
+ JSON.stringify({
+ version: 3,
+ speechModelUsed: "universal-3-5-pro",
+ durationMs: 1000,
+ languageCode: "en",
+ words: [],
+ }),
+ ),
+ ).toMatchObject({ version: 3, speechModelUsed: "universal-3-5-pro" });
+ });
+});
+
+describe("remapEditTranscriptThroughSpec", () => {
+ it("leaves word timing untouched for an identity spec", () => {
+ const transcript = createEditTranscript(assemblyAIEditResponse, 4_000);
+ const remapped = remapEditTranscriptThroughSpec(
+ transcript,
+ createIdentityEditSpec(4),
+ );
+
+ expect(remapped.durationMs).toBe(4_000);
+ expect(remapped.words).toEqual(transcript.words);
+ expect(remapped.speechModelUsed).toBe(transcript.speechModelUsed);
+ expect(remapped.languageCode).toBe(transcript.languageCode);
+ });
+
+ it("drops words whose midpoint falls inside a cut and shifts the rest", () => {
+ const transcript = createEditTranscript(assemblyAIEditResponse, 4_000);
+ const remapped = remapEditTranscriptThroughSpec(
+ transcript,
+ editSpec(4, [
+ { start: 0.45, end: 2.22 },
+ { start: 2.635, end: 4 },
+ ]),
+ );
+
+ expect(remapped.durationMs).toBe(3_135);
+ expect(
+ remapped.words.map((word) => [word.id, word.startMs, word.endMs]),
+ ).toEqual([
+ ["word-1-520-720", 70, 270],
+ ["word-2-730-840", 280, 390],
+ ["word-3-850-910", 400, 460],
+ ["word-4-930-1130", 480, 680],
+ ["word-5-1140-1510", 690, 1_060],
+ ["word-7-2700-3070", 1_835, 2_205],
+ ["word-8-3090-3400", 2_225, 2_535],
+ ]);
+ });
+
+ it("clamps words that straddle a cut boundary instead of dropping them", () => {
+ const transcript = createEditTranscript(
+ {
+ speech_model_used: "universal-3-5-pro",
+ words: [
+ { text: "straddles", start: 800, end: 1_400 },
+ { text: "inside", start: 2_000, end: 2_200 },
+ ],
+ },
+ 4_000,
+ );
+ const remapped = remapEditTranscriptThroughSpec(
+ transcript,
+ editSpec(4, [{ start: 1, end: 3 }]),
+ );
+
+ expect(remapped.durationMs).toBe(2_000);
+ expect(remapped.words).toHaveLength(2);
+ // midpoint 1.1s is kept, and the leading 200ms outside the range is clamped
+ expect(remapped.words[0]).toMatchObject({
+ text: "straddles",
+ startMs: 0,
+ endMs: 400,
+ });
+ expect(remapped.words[1]).toMatchObject({
+ text: "inside",
+ startMs: 1_000,
+ endMs: 1_200,
+ });
+ });
+
+ it("accumulates offsets across multiple keep ranges", () => {
+ const transcript = createEditTranscript(
+ {
+ speech_model_used: "universal-3-5-pro",
+ words: [
+ { text: "one", start: 100, end: 300 },
+ { text: "two", start: 2_100, end: 2_400 },
+ { text: "three", start: 4_100, end: 4_500 },
+ { text: "cut", start: 5_200, end: 5_400 },
+ ],
+ },
+ 6_000,
+ );
+ const remapped = remapEditTranscriptThroughSpec(
+ transcript,
+ editSpec(6, [
+ { start: 0, end: 1 },
+ { start: 2, end: 3 },
+ { start: 4, end: 5 },
+ ]),
+ );
+
+ expect(remapped.durationMs).toBe(3_000);
+ expect(
+ remapped.words.map((word) => [word.text, word.startMs, word.endMs]),
+ ).toEqual([
+ ["one", 100, 300],
+ ["two", 1_100, 1_400],
+ ["three", 2_100, 2_500],
+ ]);
+ });
+
+ it("preserves ids and word metadata while remapping", () => {
+ const transcript = createEditTranscript(assemblyAIEditResponse, 4_000);
+ const remapped = remapEditTranscriptThroughSpec(
+ transcript,
+ editSpec(4, [{ start: 2, end: 4 }]),
+ );
+ const original = transcript.words.find(
+ (word) => word.id === "word-7-2700-3070",
+ );
+ const moved = remapped.words.find((word) => word.id === "word-7-2700-3070");
+
+ expect(moved).toMatchObject({
+ text: original?.text,
+ confidence: original?.confidence,
+ speaker: original?.speaker,
+ channel: original?.channel,
+ startMs: 700,
+ endMs: 1_070,
+ });
+ });
+
+ it("drops every word when the spec keeps nothing", () => {
+ const transcript = createEditTranscript(assemblyAIEditResponse, 4_000);
+ const remapped = remapEditTranscriptThroughSpec(
+ transcript,
+ editSpec(4, []),
+ );
+
+ expect(remapped).toMatchObject({ durationMs: 0, words: [] });
+ });
+
+ it("keeps remapped words sorted and parseable", () => {
+ const transcript = createEditTranscript(
+ assemblyAIRealFillerResponse,
+ 8_000,
+ );
+ const remapped = remapEditTranscriptThroughSpec(
+ transcript,
+ editSpec(8, [
+ { start: 1, end: 3.3 },
+ { start: 4, end: 8 },
+ ]),
+ );
+
+ expect(remapped.durationMs).toBe(6_300);
+ for (let index = 1; index < remapped.words.length; index++) {
+ const previous = remapped.words[index - 1];
+ const current = remapped.words[index];
+ expect(current?.startMs).toBeGreaterThanOrEqual(previous?.startMs ?? 0);
+ expect(current?.endMs).toBeGreaterThan(current?.startMs ?? 0);
+ expect(current?.endMs).toBeLessThanOrEqual(remapped.durationMs);
+ }
+ expect(parseEditTranscript(serializeEditTranscript(remapped))).toEqual(
+ remapped,
+ );
+ });
+});
+
+describe("editTranscriptWordsToCaptionVtt", () => {
+ it("strips fillers from captions built off the verbatim words", () => {
+ const transcript = createEditTranscript(assemblyAIEditResponse, 4_000);
+ const vtt = editTranscriptWordsToCaptionVtt(transcript.words);
+
+ expect(vtt.startsWith("WEBVTT\n\n")).toBe(true);
+ expect(vtt).not.toContain("Um,");
+ expect(vtt).not.toContain("Erm");
+ expect(vtt).toContain("this is a real example.");
+ expect(vtt).toContain("00:00:00.520 --> 00:00:01.510");
+ expect(vtt).toContain("nothing else.");
+ });
+
+ it("returns a header-only VTT when there are no words", () => {
+ expect(editTranscriptWordsToCaptionVtt([])).toBe("WEBVTT\n\n");
+ });
+});
diff --git a/apps/web/lib/edit-transcript.ts b/apps/web/lib/edit-transcript.ts
new file mode 100644
index 000000000..cf06b9ae4
--- /dev/null
+++ b/apps/web/lib/edit-transcript.ts
@@ -0,0 +1,678 @@
+import type { VideoEditRange, VideoEditSpec } from "@cap/database/types";
+import { formatToWebVTT } from "@/lib/transcribe-utils";
+import {
+ getEditSpecOutputDuration,
+ mapSourceTimeToOutputTime,
+ normalizeKeepRanges,
+} from "@/lib/video-edits";
+
+/**
+ * Stored word transcripts are always expressed in the ORIGINAL media timeline
+ * (the mp4 preserved at `videoEdits.sourceKey`) and are immutable across edits.
+ * Everything shown for the current output is derived by remapping the stored
+ * words through the video's cumulative edit spec.
+ */
+export const EDIT_TRANSCRIPT_VERSION = 3;
+export const EDIT_TRANSCRIPT_KEY_SUFFIX = "transcription.edit.v3.json";
+export const EDIT_TRANSCRIPT_STATUS_KEY_SUFFIX =
+ "transcription.edit.v3.status.json";
+
+export type EditTranscriptBackfillStatus = {
+ status: "processing" | "error";
+ requestId: string;
+ requestedAt: string;
+};
+
+const MAX_CUT_PADDING_MS = 80;
+const MIN_PLAYABLE_DURATION_MS = 50;
+const UNKNOWN_SPEECH_MODEL = "unknown";
+
+export type EditTranscriptWord = {
+ id: string;
+ text: string;
+ startMs: number;
+ endMs: number;
+ confidence: number | null;
+ speaker: string | null;
+ channel: string | null;
+};
+
+export type EditTranscript = {
+ version: typeof EDIT_TRANSCRIPT_VERSION;
+ speechModelUsed: string;
+ durationMs: number;
+ languageCode: string | null;
+ words: EditTranscriptWord[];
+};
+
+export type EditTranscriptGroup = {
+ id: string;
+ startIndex: number;
+ endIndex: number;
+ startMs: number;
+ endMs: number;
+};
+
+export type TranscriptCutPlan = {
+ startMs: number;
+ endMs: number;
+ safe: boolean;
+ reason: "overlapping-speech" | "no-playable-output" | null;
+};
+
+export type FillerCutPlan = {
+ ranges: TranscriptCutPlan[];
+ fillerCount: number;
+ skippedCount: number;
+};
+
+export type AssemblyAIEditWord = {
+ text?: unknown;
+ start?: unknown;
+ end?: unknown;
+ confidence?: unknown;
+ speaker?: unknown;
+ channel?: unknown;
+};
+
+export type AssemblyAIEditResult = {
+ words?: readonly AssemblyAIEditWord[] | null;
+ language_code?: unknown;
+ speech_model_used?: unknown;
+};
+
+const wordMaxEndIndexes = new WeakMap<
+ readonly EditTranscriptWord[],
+ { endMs: number; index: number }[]
+>();
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null;
+}
+
+function finiteNumber(value: unknown) {
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
+}
+
+function nullableString(value: unknown) {
+ if (typeof value === "string" && value.length > 0) return value;
+ if (typeof value === "number" && Number.isFinite(value)) return `${value}`;
+ return null;
+}
+
+function clampMilliseconds(value: number, durationMs: number) {
+ return Math.min(Math.max(Math.round(value), 0), durationMs);
+}
+
+function normalizeToken(text: string) {
+ return text
+ .trim()
+ .toLocaleLowerCase()
+ .replace(/^[\p{P}\p{S}]+|[\p{P}\p{S}]+$/gu, "");
+}
+
+function isExactFillerToken(token: string) {
+ return (
+ /^u+m+$/.test(token) ||
+ /^u+h+$/.test(token) ||
+ /^e+rm+$/.test(token) ||
+ token === "er" ||
+ /^a+h+$/.test(token) ||
+ /^h+m+$/.test(token)
+ );
+}
+
+export function isFillerWord(text: string) {
+ return isExactFillerToken(normalizeToken(text));
+}
+
+export function createEditTranscript(
+ result: AssemblyAIEditResult,
+ durationMs: number,
+): EditTranscript {
+ const safeDurationMs =
+ Number.isFinite(durationMs) && durationMs > 0 ? Math.round(durationMs) : 0;
+ const candidates = (result.words ?? [])
+ .map((word, originalIndex) => {
+ const text = typeof word.text === "string" ? word.text.trim() : "";
+ const rawStart = finiteNumber(word.start);
+ const rawEnd = finiteNumber(word.end);
+ if (!text || rawStart === null || rawEnd === null) return null;
+
+ const startMs = clampMilliseconds(
+ Math.min(rawStart, rawEnd),
+ safeDurationMs,
+ );
+ const endMs = clampMilliseconds(
+ Math.max(rawStart, rawEnd),
+ safeDurationMs,
+ );
+ if (endMs <= startMs) return null;
+
+ const rawConfidence = finiteNumber(word.confidence);
+ return {
+ originalIndex,
+ text,
+ startMs,
+ endMs,
+ confidence:
+ rawConfidence === null
+ ? null
+ : Math.min(Math.max(rawConfidence, 0), 1),
+ speaker: nullableString(word.speaker),
+ channel: nullableString(word.channel),
+ };
+ })
+ .filter((word): word is NonNullable<typeof word> => word !== null)
+ .sort(
+ (left, right) =>
+ left.startMs - right.startMs ||
+ left.endMs - right.endMs ||
+ left.originalIndex - right.originalIndex,
+ );
+
+ return {
+ version: EDIT_TRANSCRIPT_VERSION,
+ speechModelUsed:
+ typeof result.speech_model_used === "string" &&
+ result.speech_model_used.length > 0
+ ? result.speech_model_used
+ : UNKNOWN_SPEECH_MODEL,
+ durationMs: safeDurationMs,
+ languageCode: nullableString(result.language_code),
+ words: candidates.map(
+ ({ originalIndex: _originalIndex, ...word }, index) => ({
+ ...word,
+ id: `word-${index}-${word.startMs}-${word.endMs}`,
+ }),
+ ),
+ };
+}
+
+export function serializeEditTranscript(transcript: EditTranscript) {
+ return JSON.stringify(transcript);
+}
+
+export function parseEditTranscript(value: string): EditTranscript | null {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(value);
+ } catch {
+ return null;
+ }
+
+ if (
+ !isRecord(parsed) ||
+ parsed.version !== EDIT_TRANSCRIPT_VERSION ||
+ typeof parsed.speechModelUsed !== "string" ||
+ parsed.speechModelUsed.length === 0 ||
+ typeof parsed.durationMs !== "number" ||
+ !Number.isFinite(parsed.durationMs) ||
+ parsed.durationMs <= 0 ||
+ !Array.isArray(parsed.words)
+ ) {
+ return null;
+ }
+
+ const languageCode =
+ parsed.languageCode === null || typeof parsed.languageCode === "string"
+ ? parsed.languageCode
+ : null;
+ const words: EditTranscriptWord[] = [];
+
+ for (const value of parsed.words) {
+ if (
+ !isRecord(value) ||
+ typeof value.id !== "string" ||
+ typeof value.text !== "string" ||
+ typeof value.startMs !== "number" ||
+ typeof value.endMs !== "number" ||
+ !Number.isFinite(value.startMs) ||
+ !Number.isFinite(value.endMs) ||
+ value.startMs < 0 ||
+ value.endMs <= value.startMs ||
+ value.endMs > parsed.durationMs
+ ) {
+ return null;
+ }
+
+ words.push({
+ id: value.id,
+ text: value.text,
+ startMs: value.startMs,
+ endMs: value.endMs,
+ confidence:
+ typeof value.confidence === "number" &&
+ Number.isFinite(value.confidence)
+ ? Math.min(Math.max(value.confidence, 0), 1)
+ : null,
+ speaker: nullableString(value.speaker),
+ channel: nullableString(value.channel),
+ });
+ }
+
+ for (let index = 1; index < words.length; index++) {
+ const previous = words[index - 1];
+ const current = words[index];
+ if (
+ !previous ||
+ !current ||
+ current.startMs < previous.startMs ||
+ (current.startMs === previous.startMs && current.endMs < previous.endMs)
+ ) {
+ return null;
+ }
+ }
+
+ return {
+ version: EDIT_TRANSCRIPT_VERSION,
+ speechModelUsed: parsed.speechModelUsed,
+ durationMs: Math.round(parsed.durationMs),
+ languageCode,
+ words,
+ };
+}
+
+/**
+ * Projects a transcript stored in the ORIGINAL media timeline onto the output
+ * timeline produced by `editSpec`. Words whose midpoint falls inside a cut are
+ * dropped (same rule as {@link getDeletedTranscriptWordIds}); words that
+ * straddle a cut boundary are clamped into the keep range they belong to.
+ */
+export function remapEditTranscriptThroughSpec(
+ transcript: EditTranscript,
+ editSpec: VideoEditSpec,
+): EditTranscript {
+ const spec = normalizeKeepRanges(
+ editSpec.keepRanges,
+ editSpec.sourceDuration,
+ );
+ const durationMs = Math.round(getEditSpecOutputDuration(spec) * 1000);
+ const keepRanges = spec.keepRanges;
+ const words: EditTranscriptWord[] = [];
+ let rangeIndex = 0;
+
+ for (const word of transcript.words) {
+ const midpointSeconds = (word.startMs + word.endMs) / 2000;
+ while (
+ rangeIndex < keepRanges.length &&
+ (keepRanges[rangeIndex]?.end ?? 0) < midpointSeconds
+ ) {
+ rangeIndex++;
+ }
+
+ const range = keepRanges[rangeIndex];
+ if (
+ !range ||
+ midpointSeconds < range.start ||
+ midpointSeconds > range.end
+ ) {
+ continue;
+ }
+
+ const clampedStartSeconds = Math.min(
+ Math.max(word.startMs / 1000, range.start),
+ range.end,
+ );
+ const clampedEndSeconds = Math.min(
+ Math.max(word.endMs / 1000, range.start),
+ range.end,
+ );
+ const outputStartSeconds = mapSourceTimeToOutputTime(
+ clampedStartSeconds,
+ spec,
+ );
+ if (outputStartSeconds === null) continue;
+
+ const startMs = clampMilliseconds(outputStartSeconds * 1000, durationMs);
+ const endMs = Math.max(
+ clampMilliseconds(
+ outputStartSeconds * 1000 +
+ (clampedEndSeconds - clampedStartSeconds) * 1000,
+ durationMs,
+ ),
+ startMs + 1,
+ );
+ if (endMs > durationMs) continue;
+
+ words.push({ ...word, startMs, endMs });
+ }
+
+ words.sort(
+ (left, right) => left.startMs - right.startMs || left.endMs - right.endMs,
+ );
+
+ return {
+ version: EDIT_TRANSCRIPT_VERSION,
+ speechModelUsed: transcript.speechModelUsed,
+ durationMs,
+ languageCode: transcript.languageCode,
+ words,
+ };
+}
+
+/**
+ * Caption VTT derived from the stored words. Fillers are stripped so captions
+ * stay clean even though the stored transcript is verbatim.
+ */
+export function editTranscriptWordsToCaptionVtt(
+ words: readonly EditTranscriptWord[],
+): string {
+ return formatToWebVTT({
+ words: words
+ .filter((word) => !isFillerWord(word.text))
+ .map((word) => ({
+ text: word.text,
+ start: word.startMs,
+ end: word.endMs,
+ })),
+ });
+}
+
+export function getEditTranscriptObjectKey(ownerId: string, videoId: string) {
+ return `${ownerId}/${videoId}/${EDIT_TRANSCRIPT_KEY_SUFFIX}`;
+}
+
+export function getEditTranscriptStatusObjectKey(
+ ownerId: string,
+ videoId: string,
+) {
+ return `${ownerId}/${videoId}/${EDIT_TRANSCRIPT_STATUS_KEY_SUFFIX}`;
+}
+
+export function isPrivateEditTranscriptObjectKey(key: string) {
+ return (
+ key.endsWith(`/${EDIT_TRANSCRIPT_KEY_SUFFIX}`) ||
+ key.endsWith(`/${EDIT_TRANSCRIPT_STATUS_KEY_SUFFIX}`)
+ );
+}
+
+export function getEditTranscriptBackfillStatus(
+ metadata: unknown,
+): EditTranscriptBackfillStatus | null {
+ if (!isRecord(metadata)) return null;
+ const status = metadata.editTranscriptBackfill;
+ if (
+ !isRecord(status) ||
+ (status.status !== "processing" && status.status !== "error") ||
+ typeof status.requestId !== "string" ||
+ status.requestId.length === 0 ||
+ typeof status.requestedAt !== "string" ||
+ status.requestedAt.length === 0
+ ) {
+ return null;
+ }
+
+ return {
+ status: status.status,
+ requestId: status.requestId,
+ requestedAt: status.requestedAt,
+ };
+}
+
+export function groupEditTranscriptWords(
+ words: readonly EditTranscriptWord[],
+ maxWords = 48,
+): EditTranscriptGroup[] {
+ if (words.length === 0) return [];
+
+ const groups: EditTranscriptGroup[] = [];
+ let startIndex = 0;
+
+ for (let index = 0; index < words.length; index++) {
+ const word = words[index];
+ const nextWord = words[index + 1];
+ if (!word) continue;
+
+ const reachedLimit = index - startIndex + 1 >= maxWords;
+ const punctuationBreak = /[.!?]$/.test(word.text);
+ const silenceBreak = nextWord ? nextWord.startMs - word.endMs >= 800 : true;
+ const speakerBreak =
+ nextWord !== undefined &&
+ word.speaker !== null &&
+ nextWord.speaker !== null &&
+ word.speaker !== nextWord.speaker;
+
+ if (
+ nextWord &&
+ !reachedLimit &&
+ !punctuationBreak &&
+ !silenceBreak &&
+ !speakerBreak
+ ) {
+ continue;
+ }
+
+ groups.push({
+ id: `group-${groups.length}-${word.startMs}`,
+ startIndex,
+ endIndex: index,
+ startMs: words[startIndex]?.startMs ?? word.startMs,
+ endMs: word.endMs,
+ });
+ startIndex = index + 1;
+ }
+
+ return groups;
+}
+
+export function normalizeTranscriptSelection(
+ firstIndex: number,
+ secondIndex: number,
+ wordCount: number,
+) {
+ if (
+ !Number.isInteger(firstIndex) ||
+ !Number.isInteger(secondIndex) ||
+ wordCount <= 0
+ ) {
+ return null;
+ }
+
+ const startIndex = Math.min(firstIndex, secondIndex);
+ const endIndex = Math.max(firstIndex, secondIndex);
+ if (startIndex < 0 || endIndex >= wordCount) return null;
+ return { startIndex, endIndex };
+}
+
+export function findActiveTranscriptWordIndex(
+ words: readonly EditTranscriptWord[],
+ timeMs: number,
+) {
+ if (!Number.isFinite(timeMs) || words.length === 0) return -1;
+
+ let low = 0;
+ let high = words.length - 1;
+ let candidate = -1;
+
+ while (low <= high) {
+ const middle = Math.floor((low + high) / 2);
+ const word = words[middle];
+ if (!word) break;
+ if (word.startMs <= timeMs) {
+ candidate = middle;
+ low = middle + 1;
+ } else {
+ high = middle - 1;
+ }
+ }
+
+ if (candidate < 0) return -1;
+
+ const candidateWord = words[candidate];
+ if (candidateWord && candidateWord.endMs >= timeMs) return candidate;
+
+ let maxEndIndexes = wordMaxEndIndexes.get(words);
+ if (!maxEndIndexes) {
+ maxEndIndexes = [];
+ let maximum = { endMs: Number.NEGATIVE_INFINITY, index: -1 };
+ for (let index = 0; index < words.length; index++) {
+ const word = words[index];
+ if (word && word.endMs > maximum.endMs) {
+ maximum = { endMs: word.endMs, index };
+ }
+ maxEndIndexes.push(maximum);
+ }
+ wordMaxEndIndexes.set(words, maxEndIndexes);
+ }
+
+ const active = maxEndIndexes[candidate];
+ return active && active.endMs >= timeMs ? active.index : -1;
+}
+
+function getCutPadding(gapMs: number) {
+ return Math.max(0, Math.min(MAX_CUT_PADDING_MS, Math.floor(gapMs / 2)));
+}
+
+function overlaps(startMs: number, endMs: number, word: EditTranscriptWord) {
+ return word.startMs < endMs && word.endMs > startMs;
+}
+
+export function planTranscriptCut(
+ words: readonly EditTranscriptWord[],
+ firstIndex: number,
+ secondIndex: number,
+ durationMs: number,
+): TranscriptCutPlan | null {
+ const selection = normalizeTranscriptSelection(
+ firstIndex,
+ secondIndex,
+ words.length,
+ );
+ if (!selection || !Number.isFinite(durationMs) || durationMs <= 0)
+ return null;
+
+ const firstWord = words[selection.startIndex];
+ const lastWord = words[selection.endIndex];
+ if (!firstWord || !lastWord) return null;
+
+ const hasOutsideOverlap = words.some(
+ (word, index) =>
+ (index < selection.startIndex || index > selection.endIndex) &&
+ overlaps(firstWord.startMs, lastWord.endMs, word),
+ );
+ if (hasOutsideOverlap) {
+ return {
+ startMs: firstWord.startMs,
+ endMs: lastWord.endMs,
+ safe: false,
+ reason: "overlapping-speech",
+ };
+ }
+
+ const previousWord = words[selection.startIndex - 1];
+ const nextWord = words[selection.endIndex + 1];
+ const startPadding = getCutPadding(
+ firstWord.startMs - (previousWord?.endMs ?? 0),
+ );
+ const endPadding = getCutPadding(
+ (nextWord?.startMs ?? durationMs) - lastWord.endMs,
+ );
+ const startMs = Math.max(0, firstWord.startMs - startPadding);
+ const endMs = Math.min(durationMs, lastWord.endMs + endPadding);
+ const leavesPlayableOutput =
+ startMs >= MIN_PLAYABLE_DURATION_MS ||
+ durationMs - endMs >= MIN_PLAYABLE_DURATION_MS;
+
+ return {
+ startMs,
+ endMs,
+ safe: leavesPlayableOutput,
+ reason: leavesPlayableOutput ? null : "no-playable-output",
+ };
+}
+
+export function planFillerCuts(
+ words: readonly EditTranscriptWord[],
+ durationMs: number,
+): FillerCutPlan {
+ const ranges: TranscriptCutPlan[] = [];
+ let skippedCount = 0;
+ let previousMaxEnd = 0;
+
+ for (let index = 0; index < words.length; index++) {
+ const word = words[index];
+ if (!word) continue;
+
+ if (isFillerWord(word.text)) {
+ const nextWord = words[index + 1];
+ const overlappingSpeech =
+ previousMaxEnd > word.startMs ||
+ (nextWord !== undefined && nextWord.startMs < word.endMs);
+
+ if (overlappingSpeech) {
+ skippedCount++;
+ } else {
+ const startPadding = getCutPadding(word.startMs - previousMaxEnd);
+ const endPadding = getCutPadding(
+ (nextWord?.startMs ?? durationMs) - word.endMs,
+ );
+ ranges.push({
+ startMs: Math.max(0, word.startMs - startPadding),
+ endMs: Math.min(durationMs, word.endMs + endPadding),
+ safe: true,
+ reason: null,
+ });
+ }
+ }
+
+ previousMaxEnd = Math.max(previousMaxEnd, word.endMs);
+ }
+
+ const mergedRanges: TranscriptCutPlan[] = [];
+ for (const range of ranges) {
+ const previous = mergedRanges.at(-1);
+ if (previous && range.startMs <= previous.endMs) {
+ previous.endMs = Math.max(previous.endMs, range.endMs);
+ } else {
+ mergedRanges.push({ ...range });
+ }
+ }
+
+ const totalDeletedMs = mergedRanges.reduce(
+ (total, range) => total + range.endMs - range.startMs,
+ 0,
+ );
+ if (durationMs - totalDeletedMs < MIN_PLAYABLE_DURATION_MS) {
+ return {
+ ranges: [],
+ fillerCount: ranges.length + skippedCount,
+ skippedCount: ranges.length + skippedCount,
+ };
+ }
+
+ return {
+ ranges: mergedRanges,
+ fillerCount: ranges.length + skippedCount,
+ skippedCount,
+ };
+}
+
+export function getDeletedTranscriptWordIds(
+ words: readonly EditTranscriptWord[],
+ keepRanges: readonly VideoEditRange[],
+) {
+ const deletedIds = new Set<string>();
+ let rangeIndex = 0;
+
+ for (const word of words) {
+ const midpointSeconds = (word.startMs + word.endMs) / 2000;
+ while (
+ rangeIndex < keepRanges.length &&
+ (keepRanges[rangeIndex]?.end ?? 0) < midpointSeconds
+ ) {
+ rangeIndex++;
+ }
+
+ const range = keepRanges[rangeIndex];
+ if (
+ !range ||
+ midpointSeconds < range.start ||
+ midpointSeconds > range.end
+ ) {
+ deletedIds.add(word.id);
+ }
+ }
+
+ return deletedIds;
+}