Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(document): make a corrected word survive its re-transcription
EtienneLescot1cc0f55a2c08
diff --git a/src/lib/ai-edition/document/transcribe.ts b/src/lib/ai-edition/document/transcribe.tsindex 3a5d0fce4..77e3de73d 100644--- a/src/lib/ai-edition/document/transcribe.ts+++ b/src/lib/ai-edition/document/transcribe.ts@@ -164,18 +164,6 @@ export async function transcribeAsset(};}-export function withTranscript(- document: AxcutDocument,- transcript: AxcutTranscript,-): AxcutDocument {- const transcripts = [- ...document.transcripts.filter((t) => t.assetId !== transcript.assetId),- transcript,- ];- return {- ...document,- transcript:- document.project.primaryAssetId === transcript.assetId ? transcript : document.transcript,- transcripts,- };-}+// `withTranscript` used to live here. It moved to `document/transcript.ts`, next to+// the other writers of the same object: it is a pure document operation, and the+// Whisper adapter is not where a caller should have to look for it.diff --git a/src/lib/ai-edition/document/transcript.test.ts b/src/lib/ai-edition/document/transcript.test.tsindex a1c872ffb..1bc1f5451 100644--- a/src/lib/ai-edition/document/transcript.test.ts+++ b/src/lib/ai-edition/document/transcript.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import type { AxcutTranscript } from "../schema";-import { setWordText } from "./transcript";+import { type AxcutTranscript, createEmptyDocument } from "../schema";+import { carryOverWordEdits, setDocumentWordText, setWordText, withTranscript } from "./transcript";function fixture(language = "en"): AxcutTranscript {return {@@ -94,9 +94,13 @@ describe("setWordText", () => {expect(result.segments.map((segment) => segment.id)).toEqual(transcript.segments.map((segment) => segment.id),);+ // The provenance pair rides along with the new text — see "setWordText+ // provenance" below for the rules it follows.expect(result.words.find((word) => word.id === "word_2")).toEqual({...originalTarget,text: "prefer",+ originalText: "use",+ source: "user",});expect(result.segments[0]).toEqual({...transcript.segments[0],@@ -288,3 +292,194 @@ describe("setWordText", () => {);});});++// ─── Provenance ──────────────────────────────────────────────────+// Every field below is what makes a correction survivable: revertible by the+// user, and carryable across a re-transcription. Without them a corrected word+// is indistinguishable from a transcribed one the moment it is written.++describe("setWordText provenance", () => {+ it("records the transcriber's text the first time a word is rewritten", () => {+ const word = setWordText(fixture(), "word_3", "OpenScreenApp").words.find(+ (w) => w.id === "word_3",+ );+ expect(word).toMatchObject({+ text: "OpenScreenApp",+ originalText: "OpenScreen",+ source: "user",+ });+ });++ it("keeps the FIRST original across later edits, so revert reaches the transcriber's text", () => {+ const once = setWordText(fixture(), "word_3", "OpenScreenApp");+ const twice = setWordText(once, "word_3", "OpenScreen Studio");+ expect(twice.words.find((w) => w.id === "word_3")).toMatchObject({+ text: "OpenScreen Studio",+ originalText: "OpenScreen",+ });+ });++ it("clears the markers when the original is typed back — that round trip IS the revert", () => {+ const edited = setWordText(fixture(), "word_3", "OpenScreenApp");+ const reverted = setWordText(edited, "word_3", "OpenScreen");+ const word = reverted.words.find((w) => w.id === "word_3");+ expect(word?.text).toBe("OpenScreen");+ expect(word).not.toHaveProperty("originalText");+ expect(word).not.toHaveProperty("source");+ });++ it("leaves a synthesized word synthesized — it has no transcribed text to revert to", () => {+ const base = fixture();+ const synth: AxcutTranscript = {+ ...base,+ words: base.words.map((w) =>+ w.id === "word_3" ? { ...w, source: "synth" as const, text: "spoken" } : w,+ ),+ };+ const word = setWordText(synth, "word_3", "rewritten").words.find((w) => w.id === "word_3");+ expect(word).toMatchObject({ text: "rewritten", source: "synth" });+ expect(word).not.toHaveProperty("originalText");+ });++ it("does not mark the untouched words", () => {+ const result = setWordText(fixture(), "word_3", "OpenScreenApp");+ for (const word of result.words.filter((w) => w.id !== "word_3")) {+ expect(word).not.toHaveProperty("source");+ }+ });+});++// ─── Document-level write ────────────────────────────────────────+// The document carries the transcript twice. A word edit that writes only one+// copy leaves the legacy mirror serving pre-edit text forever — the failure that+// closed the standalone Python editor (#469).++function makeDoc(primaryAssetId = "asset_1") {+ const base = createEmptyDocument({ title: "Test", projectId: "proj_transcript" });+ return withTranscript({ ...base, project: { ...base.project, primaryAssetId } }, fixture());+}++describe("setDocumentWordText", () => {+ it("writes BOTH the per-asset transcript and the legacy mirror", () => {+ const result = setDocumentWordText(makeDoc(), "asset_1", "word_3", "OpenScreenApp");+ const stored = result.transcripts.find((t) => t.assetId === "asset_1");+ expect(stored?.words.find((w) => w.id === "word_3")?.text).toBe("OpenScreenApp");+ expect(result.transcript?.words.find((w) => w.id === "word_3")?.text).toBe("OpenScreenApp");+ expect(result.transcript).toBe(stored);+ });++ it("leaves the mirror alone when the edited asset is not the primary one", () => {+ const doc = makeDoc("asset_other");+ const result = setDocumentWordText(doc, "asset_1", "word_3", "OpenScreenApp");+ expect(result.transcript).toBe(doc.transcript);+ expect(result.transcripts.find((t) => t.assetId === "asset_1")?.words).not.toBe(+ doc.transcripts.find((t) => t.assetId === "asset_1")?.words,+ );+ });++ it("rejects an asset with no transcript rather than writing a second one", () => {+ expect(() => setDocumentWordText(makeDoc(), "asset_missing", "word_3", "x")).toThrow(+ /no transcript/,+ );+ });++ it("keeps the input document untouched", () => {+ const doc = makeDoc();+ const before = JSON.stringify(doc);+ setDocumentWordText(doc, "asset_1", "word_3", "OpenScreenApp");+ expect(JSON.stringify(doc)).toBe(before);+ });+});++// ─── Carry-over across a re-transcription ────────────────────────++function retranscribed(words: Array<[string, string, number, number]>): AxcutTranscript {+ return {+ assetId: "asset_1",+ language: "en",+ segments: [+ {+ id: "segment_1",+ kind: "speech",+ startSec: words[0][2],+ endSec: words[words.length - 1][3],+ text: words.map(([, text]) => text).join(" "),+ wordIds: words.map(([id]) => id),+ },+ ],+ words: words.map(([id, text, startSec, endSec]) => ({+ id,+ segmentId: "segment_1",+ startSec,+ endSec,+ text,+ })),+ };+}++describe("carryOverWordEdits", () => {+ const corrected = () => setWordText(fixture(), "word_3", "OpenScreenApp");++ it("re-applies a correction when the run repeats the same mistake at the same moment", () => {+ const next = retranscribed([+ ["w1", "I", 1, 2],+ ["w2", "use", 2, 3],+ ["w3", "OpenScreen", 3.1, 3.9],+ ]);+ const result = carryOverWordEdits(corrected(), next);+ expect(result.carried).toBe(1);+ expect(result.dropped).toBe(0);+ expect(result.transcript.words.find((w) => w.id === "w3")).toMatchObject({+ text: "OpenScreenApp",+ originalText: "OpenScreen",+ source: "user",+ });+ // The segment text is rebuilt too, so the captions follow.+ expect(result.transcript.segments[0].text).toBe("I use OpenScreenApp");+ });++ it("drops the correction when the run heard something else there", () => {+ const next = retranscribed([["w3", "Open Screen", 3, 4]]);+ const result = carryOverWordEdits(corrected(), next);+ expect(result).toMatchObject({ carried: 0, dropped: 1 });+ expect(result.transcript).toBe(next);+ });++ it("drops the correction when the same word lands somewhere else entirely", () => {+ const next = retranscribed([["w3", "OpenScreen", 40, 41]]);+ expect(carryOverWordEdits(corrected(), next)).toMatchObject({ carried: 0, dropped: 1 });+ });++ it("never lands two corrections on the same new word", () => {+ // Both corrections have the SAME original text and both spans overlap the one+ // word the new run produced. Without the claim, the second would overwrite the+ // first and the count would claim two were saved.+ const previous = setWordText(+ setWordText(+ retranscribed([+ ["p1", "the", 1, 2],+ ["p2", "the", 2, 3],+ ]),+ "p1",+ "a",+ ),+ "p2",+ "an",+ );+ const result = carryOverWordEdits(previous, retranscribed([["w1", "the", 1, 3]]));+ expect(result).toMatchObject({ carried: 1, dropped: 1 });+ expect(result.transcript.words[0].text).toBe("a");+ });++ it("returns the new transcript untouched when nothing was ever corrected", () => {+ const next = retranscribed([["w1", "I", 1, 2]]);+ const result = carryOverWordEdits(fixture(), next);+ expect(result.transcript).toBe(next);+ expect(result).toMatchObject({ carried: 0, dropped: 0 });+ });++ it("handles a first-ever transcription (no previous transcript)", () => {+ const next = retranscribed([["w1", "I", 1, 2]]);+ expect(carryOverWordEdits(null, next).transcript).toBe(next);+ });+});diff --git a/src/lib/ai-edition/document/transcript.ts b/src/lib/ai-edition/document/transcript.tsindex f64588f9e..6728575b1 100644--- a/src/lib/ai-edition/document/transcript.ts+++ b/src/lib/ai-edition/document/transcript.ts@@ -1,4 +1,4 @@-import type { AxcutTranscript } from "../schema";+import type { AxcutDocument, AxcutTranscript, AxcutWord } from "../schema";const CJK_EDGE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u;const CLOSING_PUNCTUATION = /^[,.;:!?%。,、;:!?…))\]}>》」』】〕]/u;@@ -28,6 +28,27 @@ function joinSegmentText(texts: string[]): string {}, "");}+/**+ * Apply the new text to ONE word, keeping its provenance straight.+ *+ * `originalText` is the transcriber's own text, captured the first time the user+ * rewrites the word and never overwritten afterwards — a second edit still reverts+ * to what Whisper said, not to the first correction. Typing the original back+ * clears the pair, so a round trip leaves no word flagged as corrected whose+ * correction is a no-op.+ */+function rewriteWord(word: AxcutWord, text: string): AxcutWord {+ // A synthesized word has no transcribed text behind it, so there is nothing to+ // revert to and nothing to record: rewriting one leaves it synthesized.+ if (word.source === "synth") return { ...word, text };+ const original = word.originalText ?? word.text;+ if (text === original) {+ const { originalText: _reverted, source: _wasUser, ...rest } = word;+ return { ...rest, text };+ }+ return { ...word, text, originalText: original, source: "user" };+}+export function setWordText(transcript: AxcutTranscript,wordId: string,@@ -63,7 +84,9 @@ export function setWordText(}}- const words = transcript.words.map((word) => (word.id === wordId ? { ...word, text } : word));+ const words = transcript.words.map((word) =>+ word.id === wordId ? rewriteWord(word, text) : word,+ );const updatedWordsById = new Map(words.map((word) => [word.id, word]));const segmentText = joinSegmentText(owningSegment.wordIds.map(@@ -76,3 +99,104 @@ export function setWordText(return { ...transcript, words, segments };}++/**+ * Write a transcript into the document — the ONLY safe way to do it.+ *+ * The document carries the same transcript twice: the per-asset `transcripts[]`+ * entry, and the legacy `transcript` mirror that a couple of readers still fall+ * back to. Writing one without the other leaves two divergent copies on disk,+ * where the mirror keeps serving the pre-edit text forever. Nothing outside this+ * function may assemble that pair.+ *+ * Lives here rather than in `transcribe.ts` (which re-exports it for its existing+ * importers): it is a pure document operation, and the Whisper adapter is not the+ * place a caller should have to look for it.+ */+export function withTranscript(+ document: AxcutDocument,+ transcript: AxcutTranscript,+): AxcutDocument {+ const transcripts = [+ ...document.transcripts.filter((t) => t.assetId !== transcript.assetId),+ transcript,+ ];+ return {+ ...document,+ transcript:+ document.project.primaryAssetId === transcript.assetId ? transcript : document.transcript,+ transcripts,+ };+}++/**+ * {@link setWordText}, addressed the way the UI has it: an asset and a word, not a+ * transcript object. Goes through `withTranscript`, so a caller cannot forget the+ * legacy mirror.+ */+export function setDocumentWordText(+ document: AxcutDocument,+ assetId: string,+ wordId: string,+ text: string,+): AxcutDocument {+ const transcript = document.transcripts.find((t) => t.assetId === assetId);+ if (!transcript) {+ throw new Error(`Cannot edit a word of asset "${assetId}": it has no transcript`);+ }+ return withTranscript(document, setWordText(transcript, wordId, text));+}++/** What {@link carryOverWordEdits} managed to save from the previous transcript. */+export interface WordEditCarryOver {+ transcript: AxcutTranscript;+ /** Corrections re-applied to the new transcript. */+ carried: number;+ /** Corrections the new transcript left no place for. These are lost. */+ dropped: number;+}++/**+ * Re-apply the user's word corrections onto a freshly transcribed transcript.+ *+ * A transcription run REPLACES the asset's transcript wholesale, so without this a+ * user who fixed twenty proper nouns and then regenerated lost all twenty, silently.+ *+ * The match is deliberately strict — same original text, overlapping span, one new+ * word per correction. A correction is carried only when the new run reproduced the+ * very same mistake at the very same moment; re-transcribing in another language+ * therefore carries nothing rather than stamping French corrections onto Spanish+ * words. What could not be carried is counted, not guessed at, so the caller can say+ * so.+ */+export function carryOverWordEdits(+ previous: AxcutTranscript | null | undefined,+ next: AxcutTranscript,+): WordEditCarryOver {+ const edits = (previous?.words ?? []).filter(+ (word) => word.source === "user" && word.originalText !== undefined,+ );+ if (edits.length === 0) return { transcript: next, carried: 0, dropped: 0 };++ // Candidates are read from `next` throughout, never from the transcript being+ // built up: a word already rewritten by an earlier correction no longer carries+ // the text the next one matches on, and `claimed` is what stops two corrections+ // from landing on the same word.+ const claimed = new Set<string>();+ let transcript = next;+ let carried = 0;+ for (const edit of edits) {+ const match = next.words.find(+ (word) =>+ !claimed.has(word.id) &&+ word.text === edit.originalText &&+ word.endSec > edit.startSec &&+ word.startSec < edit.endSec,+ );+ if (!match) continue;+ claimed.add(match.id);+ transcript = setWordText(transcript, match.id, edit.text);+ carried += 1;+ }+ return { transcript, carried, dropped: edits.length - carried };+}diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.tsindex 4f32d52bc..bbf1d6820 100644--- a/src/lib/ai-edition/schema/index.ts+++ b/src/lib/ai-edition/schema/index.ts@@ -63,6 +63,23 @@ export const wordSchema = zstartSec: z.number().nonnegative(),endSec: z.number().nonnegative(),text: z.string(),+ // Provenance of the TEXT, so a hand-corrected word can be told from a+ // transcribed one. Both fields are additive and absent on every document+ // written before them (like `cameraTrack.width`), so no schema bump: an+ // older build simply drops them on save.+ //+ // `document/transcript.ts` is the only writer, and it keeps the pair+ // consistent: `originalText` is set from the ASR text the first time a user+ // rewrites the word and never overwritten afterwards, so it stays the revert+ // target however many times the word is edited; typing the original back+ // clears both, which IS the revert.+ //+ // Absent `source` means the word came from the transcriber. It is what makes+ // a re-transcription able to carry the user's corrections forward+ // (`carryOverWordEdits`) instead of silently discarding them — and what a+ // future TTS pass will read to know which words it has to speak.+ originalText: z.string().optional(),+ source: z.enum(["asr", "user", "synth"]).optional(),}).refine((data) => data.endSec >= data.startSec, {message: "endSec must be greater than or equal to startSec",diff --git a/src/lib/ai-edition/store/transcriptionStore.ts b/src/lib/ai-edition/store/transcriptionStore.tsindex 19aeff9b6..c0baaac48 100644--- a/src/lib/ai-edition/store/transcriptionStore.ts+++ b/src/lib/ai-edition/store/transcriptionStore.ts@@ -26,7 +26,8 @@ import { useEffect, useMemo } from "react";import { toast } from "sonner";import { create } from "zustand";import { toastText as translateToast } from "@/i18n/toastText";-import { transcribeAsset, withTranscript } from "../document/transcribe";+import { transcribeAsset } from "../document/transcribe";+import { carryOverWordEdits, withTranscript } from "../document/transcript";import type { AxcutDocument } from "../schema";import {type AssetTranscriptionView,@@ -410,6 +411,20 @@ async function runJob(assetId: string, job: TranscriptionJob): Promise<void> {dropJob(assetId, runId);return;}+ // A run REPLACES the asset's transcript, so any word the user had corrected by+ // hand would go with it. Carry those corrections onto the new words first —+ // strictly, so nothing is invented (see `carryOverWordEdits`). What could not be+ // carried is lost; telling the user so is the UI's job, and there is no surface+ // for it yet.+ const merged = carryOverWordEdits(+ current.transcripts.find((t) => t.assetId === assetId),+ transcript,+ );+ if (merged.dropped > 0) {+ console.warn(+ `[transcription] ${merged.dropped} word correction(s) on asset ${assetId} could not be carried over to the new transcript.`,+ );+ }// One save: the transcript, and (on a successful retry) the removal of// the verdict remembered on the asset.// `history: false`: a transcript landing from a background job is not an edit@@ -423,7 +438,7 @@ async function runJob(assetId: string, job: TranscriptionJob): Promise<void> {a.id === assetId && a.transcriptionFailure ? { ...a, transcriptionFailure: null } : a,),},- transcript,+ merged.transcript,),{ history: false },);