Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: keep translated captions through the final cue

Richie McIlroy9d5bfdb9758f
diff --git a/apps/web/__tests__/unit/translation-vtt.test.ts b/apps/web/__tests__/unit/translation-vtt.test.ts
new file mode 100644
index 000000000..bfd78d7d0
--- /dev/null
+++ b/apps/web/__tests__/unit/translation-vtt.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from "vitest";
+import {
+ isCompleteTranslation,
+ joinTranslationChunks,
+ splitTranslationChunks,
+} from "@/actions/videos/translation-vtt";
+
+const source = `WEBVTT
+
+1
+00:00:00.000 --> 00:00:02.000
+Hello there
+
+2
+00:00:02.000 --> 00:00:04.000
+How are you?
+
+3
+00:00:04.000 --> 00:00:06.000
+See you soon`;
+
+describe("translation VTT completeness", () => {
+ it("rejects a translated file that stops before the original", () => {
+ const truncated = source.replace(/\n\n3\n[\s\S]*$/, "");
+ expect(isCompleteTranslation(source, truncated)).toBe(false);
+ });
+
+ it("rejects changed cue timing and empty cue text", () => {
+ expect(
+ isCompleteTranslation(
+ source,
+ source.replace("00:00:04.000", "00:00:04.100"),
+ ),
+ ).toBe(false);
+ expect(
+ isCompleteTranslation(source, source.replace("How are you?", "")),
+ ).toBe(false);
+ expect(
+ isCompleteTranslation(source, source.replace("\n2\n", "\n9\n")),
+ ).toBe(false);
+ });
+
+ it("joins long translations without dropping the final cue", () => {
+ const timestamp = (seconds: number) =>
+ `00:${String(Math.floor(seconds / 60)).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}.000`;
+ const cues = Array.from({ length: 180 }, (_, index) => {
+ return `${index + 1}\n${timestamp(index)} --> ${timestamp(index + 1)}\nCaption ${index + 1} with enough text to require multiple chunks`;
+ });
+ const longSource = `WEBVTT\n\n${cues.join("\n\n")}`;
+ const chunks = splitTranslationChunks(longSource);
+ expect(chunks?.length).toBeGreaterThan(1);
+ if (!chunks) throw new Error("Expected chunks");
+
+ const translations = chunks.map((chunk) =>
+ chunk.replaceAll("Caption", "Translated caption"),
+ );
+ const result = joinTranslationChunks(longSource, chunks, translations);
+ expect(result).not.toBeNull();
+ expect(isCompleteTranslation(longSource, result ?? "")).toBe(true);
+ expect(result).toContain("Translated caption 180");
+ });
+
+ it("rejects an incomplete chunk without returning a partial file", () => {
+ const chunks = splitTranslationChunks(source);
+ if (!chunks) throw new Error("Expected chunks");
+ expect(joinTranslationChunks(source, chunks, ["WEBVTT"])).toBeNull();
+ });
+});
diff --git a/apps/web/actions/videos/translate-transcript.ts b/apps/web/actions/videos/translate-transcript.ts
index f3f78d388..614e260c0 100644
--- a/apps/web/actions/videos/translate-transcript.ts
+++ b/apps/web/actions/videos/translate-transcript.ts
@@ -17,6 +17,11 @@ import {
type LanguageCode,
SUPPORTED_LANGUAGES,
} from "./translation-languages";
+import {
+ isCompleteTranslation,
+ joinTranslationChunks,
+ splitTranslationChunks,
+} from "./translation-vtt";
interface TranslateResult {
success: boolean;
@@ -75,6 +80,19 @@ export async function translateTranscript(
const translatedKey = `${video.ownerId}/${videoId}/transcription.${targetLanguage}.vtt`;
+ const originalVtt = await Effect.gen(function* () {
+ const [bucket] = yield* Storage.getAccessForVideo(
+ decodeStorageVideo(video),
+ );
+ return yield* bucket.getObject(
+ `${video.ownerId}/${videoId}/transcription.vtt`,
+ );
+ }).pipe(runPromise);
+
+ if (Option.isNone(originalVtt)) {
+ return { success: false, message: "Original transcript not found" };
+ }
+
try {
const existingTranslation = await Effect.gen(function* () {
const [bucket] = yield* Storage.getAccessForVideo(
@@ -83,7 +101,10 @@ export async function translateTranscript(
return yield* bucket.getObject(translatedKey);
}).pipe(runPromise);
- if (Option.isSome(existingTranslation)) {
+ if (
+ Option.isSome(existingTranslation) &&
+ isCompleteTranslation(originalVtt.value, existingTranslation.value)
+ ) {
return {
success: true,
translatedVtt: existingTranslation.value,
@@ -94,19 +115,6 @@ export async function translateTranscript(
console.debug("[translateTranscript] No cached translation found:", e);
}
- const originalVtt = await Effect.gen(function* () {
- const [bucket] = yield* Storage.getAccessForVideo(
- decodeStorageVideo(video),
- );
- return yield* bucket.getObject(
- `${video.ownerId}/${videoId}/transcription.vtt`,
- );
- }).pipe(runPromise);
-
- if (Option.isNone(originalVtt)) {
- return { success: false, message: "Original transcript not found" };
- }
-
const translatedVtt = await translateVttContent(
originalVtt.value,
targetLanguage,
@@ -141,8 +149,12 @@ async function translateVttContent(
targetLanguage: LanguageCode,
): Promise<string | null> {
const targetLanguageName = SUPPORTED_LANGUAGES[targetLanguage];
+ const chunks = splitTranslationChunks(vttContent);
+ if (!chunks) return null;
- const prompt = `Translate the following WebVTT subtitle file to ${targetLanguageName}.
+ const translations: string[] = [];
+ for (const chunk of chunks) {
+ const prompt = `Translate the following WebVTT subtitle file to ${targetLanguageName}.
IMPORTANT RULES:
1. Keep the "WEBVTT" header exactly as is
@@ -155,27 +167,35 @@ IMPORTANT RULES:
VTT content to translate:
-${vttContent}`;
-
- try {
- return await runWithAiProviders("generation", async (selection) => {
- const response = await generateText({
- model: selection.model(),
- prompt,
- maxOutputTokens: 8000,
- ...(selection.supportsTemperature ? { temperature: 0.3 } : {}),
- });
-
- // Validate inside the provider loop so a fulfilled response that
- // dropped the WEBVTT header falls through to the next provider.
- if (!response.text.includes("WEBVTT")) {
- throw new Error("translation response did not contain WEBVTT");
- }
-
- return response.text.trim();
- });
- } catch (error) {
- console.error("[translateVttContent] Translation error:", error);
- return null;
+${chunk}`;
+
+ try {
+ const translatedChunk = await runWithAiProviders(
+ "generation",
+ async (selection) => {
+ const response = await generateText({
+ model: selection.model(),
+ prompt,
+ maxOutputTokens: 8000,
+ ...(selection.supportsTemperature ? { temperature: 0.3 } : {}),
+ });
+
+ if (
+ response.finishReason === "length" ||
+ !isCompleteTranslation(chunk, response.text)
+ ) {
+ throw new Error("translation response has missing or changed cues");
+ }
+
+ return response.text.trim();
+ },
+ );
+ translations.push(translatedChunk);
+ } catch (error) {
+ console.error("[translateVttContent] Translation error:", error);
+ return null;
+ }
}
+
+ return joinTranslationChunks(vttContent, chunks, translations);
}
diff --git a/apps/web/actions/videos/translation-vtt.ts b/apps/web/actions/videos/translation-vtt.ts
new file mode 100644
index 000000000..3728a47db
--- /dev/null
+++ b/apps/web/actions/videos/translation-vtt.ts
@@ -0,0 +1,118 @@
+const MAX_CHUNK_LENGTH = 3_000;
+
+function splitVtt(content: string): string[] | null {
+ const blocks = content
+ .replace(/\r\n?/g, "\n")
+ .trim()
+ .split(/\n{2,}/);
+ if (!blocks[0]?.startsWith("WEBVTT") || blocks.length < 2) {
+ return null;
+ }
+ return blocks;
+}
+
+function timestampLines(block: string): string[] {
+ return block.split("\n").filter((line) => line.includes("-->"));
+}
+
+function hasCueText(block: string): boolean {
+ const lines = block.split("\n");
+ const timestampIndex = lines.findIndex((line) => line.includes("-->"));
+ return (
+ timestampIndex >= 0 &&
+ lines.slice(timestampIndex + 1).some((line) => line.trim().length > 0)
+ );
+}
+
+function cueIdentifier(block: string): string {
+ const lines = block.split("\n");
+ const timestampIndex = lines.findIndex((line) => line.includes("-->"));
+ return lines.slice(0, timestampIndex).join("\n");
+}
+
+export function isCompleteTranslation(
+ source: string,
+ translation: string,
+): boolean {
+ const sourceBlocks = splitVtt(source);
+ const translatedBlocks = splitVtt(translation);
+ if (
+ !sourceBlocks ||
+ !translatedBlocks ||
+ sourceBlocks.length !== translatedBlocks.length
+ ) {
+ return false;
+ }
+
+ for (let index = 1; index < sourceBlocks.length; index++) {
+ const original = sourceBlocks[index];
+ const translated = translatedBlocks[index];
+ if (!original || !translated) return false;
+
+ const originalTimestamps = timestampLines(original);
+ const translatedTimestamps = timestampLines(translated);
+ if (
+ originalTimestamps.length !== translatedTimestamps.length ||
+ originalTimestamps.some(
+ (line, timestampIndex) => line !== translatedTimestamps[timestampIndex],
+ ) ||
+ (originalTimestamps.length > 0 &&
+ cueIdentifier(original) !== cueIdentifier(translated)) ||
+ (originalTimestamps.length === 0 && original !== translated) ||
+ (originalTimestamps.length > 0 && !hasCueText(translated))
+ ) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+export function splitTranslationChunks(source: string): string[] | null {
+ const blocks = splitVtt(source);
+ if (!blocks) return null;
+
+ const chunks: string[] = [];
+ let current: string[] = [];
+ let length = 0;
+
+ for (const block of blocks.slice(1)) {
+ if (current.length > 0 && length + block.length > MAX_CHUNK_LENGTH) {
+ chunks.push(`WEBVTT\n\n${current.join("\n\n")}`);
+ current = [];
+ length = 0;
+ }
+ current.push(block);
+ length += block.length + 2;
+ }
+
+ if (current.length > 0) {
+ chunks.push(`WEBVTT\n\n${current.join("\n\n")}`);
+ }
+
+ return chunks;
+}
+
+export function joinTranslationChunks(
+ source: string,
+ chunks: string[],
+ translations: string[],
+): string | null {
+ const sourceBlocks = splitVtt(source);
+ if (!sourceBlocks || chunks.length !== translations.length) return null;
+
+ const translatedBlocks: string[] = [];
+ for (let index = 0; index < chunks.length; index++) {
+ const chunk = chunks[index];
+ const translation = translations[index];
+ if (!chunk || !translation || !isCompleteTranslation(chunk, translation)) {
+ return null;
+ }
+ const blocks = splitVtt(translation);
+ if (!blocks) return null;
+ translatedBlocks.push(...blocks.slice(1));
+ }
+
+ const result = `${sourceBlocks[0]}\n\n${translatedBlocks.join("\n\n")}`;
+ return isCompleteTranslation(source, result) ? result : null;
+}