Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: invalidate cached caption translations after transcript edits and allow empty transcripts

Richie McIlroy569e227bd2eb
diff --git a/apps/web/__tests__/unit/translation-vtt.test.ts b/apps/web/__tests__/unit/translation-vtt.test.ts
index bfd78d7d0..dc366e92a 100644
--- a/apps/web/__tests__/unit/translation-vtt.test.ts
+++ b/apps/web/__tests__/unit/translation-vtt.test.ts
@@ -2,7 +2,9 @@ import { describe, expect, it } from "vitest";
import {
isCompleteTranslation,
joinTranslationChunks,
+ readCachedTranslation,
splitTranslationChunks,
+ withSourceFingerprint,
} from "@/actions/videos/translation-vtt";
const source = `WEBVTT
@@ -65,4 +67,24 @@ describe("translation VTT completeness", () => {
if (!chunks) throw new Error("Expected chunks");
expect(joinTranslationChunks(source, chunks, ["WEBVTT"])).toBeNull();
});
+
+ it("translates a header-only transcript without any chunks", () => {
+ const empty = "WEBVTT\n\n";
+ const chunks = splitTranslationChunks(empty);
+ expect(chunks).toEqual([]);
+ expect(joinTranslationChunks(empty, [], [])).toBe("WEBVTT");
+ expect(isCompleteTranslation(empty, "WEBVTT")).toBe(true);
+ });
+
+ it("reuses a cached translation only for the transcript it was made from", () => {
+ const translated = source.replaceAll("Hello there", "Hola");
+ const cached = withSourceFingerprint(source, translated);
+ if (!cached) throw new Error("Expected cache body");
+
+ expect(readCachedTranslation(source, cached)).toBe(translated);
+ expect(
+ readCachedTranslation(source.replace("See you soon", "Bye"), cached),
+ ).toBeNull();
+ expect(readCachedTranslation(source, translated)).toBeNull();
+ });
});
diff --git a/apps/web/actions/videos/translate-transcript.ts b/apps/web/actions/videos/translate-transcript.ts
index 614e260c0..4c03c8feb 100644
--- a/apps/web/actions/videos/translate-transcript.ts
+++ b/apps/web/actions/videos/translate-transcript.ts
@@ -20,7 +20,9 @@ import {
import {
isCompleteTranslation,
joinTranslationChunks,
+ readCachedTranslation,
splitTranslationChunks,
+ withSourceFingerprint,
} from "./translation-vtt";
interface TranslateResult {
@@ -101,13 +103,13 @@ export async function translateTranscript(
return yield* bucket.getObject(translatedKey);
}).pipe(runPromise);
- if (
- Option.isSome(existingTranslation) &&
- isCompleteTranslation(originalVtt.value, existingTranslation.value)
- ) {
+ const cachedTranslation = Option.isSome(existingTranslation)
+ ? readCachedTranslation(originalVtt.value, existingTranslation.value)
+ : null;
+ if (cachedTranslation) {
return {
success: true,
- translatedVtt: existingTranslation.value,
+ translatedVtt: cachedTranslation,
message: "Retrieved cached translation",
};
}
@@ -124,17 +126,23 @@ export async function translateTranscript(
return { success: false, message: "Translation failed" };
}
- try {
- await Effect.gen(function* () {
- const [bucket] = yield* Storage.getAccessForVideo(
- decodeStorageVideo(video),
+ const cacheBody = withSourceFingerprint(originalVtt.value, translatedVtt);
+ if (cacheBody) {
+ try {
+ await Effect.gen(function* () {
+ const [bucket] = yield* Storage.getAccessForVideo(
+ decodeStorageVideo(video),
+ );
+ yield* bucket.putObject(translatedKey, cacheBody, {
+ contentType: "text/vtt",
+ });
+ }).pipe(runPromise);
+ } catch (error) {
+ console.error(
+ "[translateTranscript] Failed to cache translation:",
+ error,
);
- yield* bucket.putObject(translatedKey, translatedVtt, {
- contentType: "text/vtt",
- });
- }).pipe(runPromise);
- } catch (error) {
- console.error("[translateTranscript] Failed to cache translation:", error);
+ }
}
return {
diff --git a/apps/web/actions/videos/translation-vtt.ts b/apps/web/actions/videos/translation-vtt.ts
index 3728a47db..3fa7cbaf5 100644
--- a/apps/web/actions/videos/translation-vtt.ts
+++ b/apps/web/actions/videos/translation-vtt.ts
@@ -1,11 +1,14 @@
+import { createHash } from "node:crypto";
+
const MAX_CHUNK_LENGTH = 3_000;
+const SOURCE_FINGERPRINT_PREFIX = "NOTE cap-source-sha256 ";
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) {
+ if (!blocks[0]?.startsWith("WEBVTT")) {
return null;
}
return blocks;
@@ -113,6 +116,30 @@ export function joinTranslationChunks(
translatedBlocks.push(...blocks.slice(1));
}
- const result = `${sourceBlocks[0]}\n\n${translatedBlocks.join("\n\n")}`;
+ const result = [sourceBlocks[0], ...translatedBlocks].join("\n\n");
return isCompleteTranslation(source, result) ? result : null;
}
+
+function sourceFingerprint(source: string): string {
+ return `${SOURCE_FINGERPRINT_PREFIX}${createHash("sha256").update(source).digest("hex")}`;
+}
+
+export function withSourceFingerprint(
+ source: string,
+ translation: string,
+): string | null {
+ const blocks = splitVtt(translation);
+ if (!blocks) return null;
+ const [header, ...cues] = blocks;
+ return [header, sourceFingerprint(source), ...cues].join("\n\n");
+}
+
+export function readCachedTranslation(
+ source: string,
+ cached: string,
+): string | null {
+ const blocks = splitVtt(cached);
+ if (!blocks || blocks[1] !== sourceFingerprint(source)) return null;
+ const translation = [blocks[0], ...blocks.slice(2)].join("\n\n");
+ return isCompleteTranslation(source, translation) ? translation : null;
+}