From e2d34763b8dc3689edfddfea478c51cfa614464e Mon Sep 17 00:00:00 2001 From: auberginewly <3127221787@qq.com> Date: Wed, 28 Oct 2026 18:10:43 +0800 Subject: [PATCH 1/5] feat(transcript): import source-timed SRT subtitles --- .../ai-edition/ImportSrtDialog.test.tsx | 201 ++++++++++++++++++ src/components/ai-edition/ImportSrtDialog.tsx | 200 +++++++++++++++++ src/components/ai-edition/RightPanes.tsx | 26 ++- src/i18n/locales/ar/settings.json | 28 ++- src/i18n/locales/cs/settings.json | 28 ++- src/i18n/locales/de/settings.json | 28 ++- src/i18n/locales/en/settings.json | 28 ++- src/i18n/locales/es/settings.json | 28 ++- src/i18n/locales/fr/settings.json | 28 ++- src/i18n/locales/it/settings.json | 28 ++- src/i18n/locales/ja-JP/settings.json | 28 ++- src/i18n/locales/ko-KR/settings.json | 28 ++- src/i18n/locales/pt-BR/settings.json | 28 ++- src/i18n/locales/ru/settings.json | 28 ++- src/i18n/locales/tr/settings.json | 28 ++- src/i18n/locales/vi/settings.json | 28 ++- src/i18n/locales/zh-CN/settings.json | 28 ++- src/i18n/locales/zh-TW/settings.json | 28 ++- src/lib/ai-edition/captions/cues.ts | 18 ++ src/lib/ai-edition/captions/translations.ts | 5 +- src/lib/ai-edition/schema/index.ts | 3 + .../store/documentWriteAudit.test.ts | 3 + .../ai-edition/store/transcriptImport.test.ts | 37 ++++ src/lib/ai-edition/store/transcriptImport.ts | 33 +++ .../ai-edition/store/transcriptionStore.ts | 10 +- .../ai-edition/transcription/fromSrt.test.ts | 44 ++++ src/lib/ai-edition/transcription/fromSrt.ts | 82 +++++++ .../transcription/srtCaptions.test.ts | 77 +++++++ 28 files changed, 1139 insertions(+), 20 deletions(-) create mode 100644 src/components/ai-edition/ImportSrtDialog.test.tsx create mode 100644 src/components/ai-edition/ImportSrtDialog.tsx create mode 100644 src/lib/ai-edition/store/transcriptImport.test.ts create mode 100644 src/lib/ai-edition/store/transcriptImport.ts create mode 100644 src/lib/ai-edition/transcription/fromSrt.test.ts create mode 100644 src/lib/ai-edition/transcription/fromSrt.ts create mode 100644 src/lib/ai-edition/transcription/srtCaptions.test.ts diff --git a/src/components/ai-edition/ImportSrtDialog.test.tsx b/src/components/ai-edition/ImportSrtDialog.test.tsx new file mode 100644 index 0000000000..556fcb9755 --- /dev/null +++ b/src/components/ai-edition/ImportSrtDialog.test.tsx @@ -0,0 +1,201 @@ +// @vitest-environment jsdom +import "@testing-library/jest-dom"; +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { I18nProvider } from "@/contexts/I18nContext"; +import { documentSchema } from "@/lib/ai-edition/schema"; +import { useProjectStore } from "@/lib/ai-edition/store/projectStore"; +import { useTranscriptionStore } from "@/lib/ai-edition/store/transcriptionStore"; +import { redo, undo } from "@/lib/ai-edition/store/undo"; +import { clearHistory, past } from "@/lib/ai-edition/store/undoStack"; +import { transcriptFromSrt } from "@/lib/ai-edition/transcription/fromSrt"; +import { ImportSrtDialog } from "./ImportSrtDialog"; + +const mocks = vi.hoisted(() => ({ save: vi.fn() })); +vi.mock("@/native/client", () => ({ nativeBridgeClient: { aiEdition: { save: mocks.save } } })); +vi.mock("sonner", () => ({ toast: { error: vi.fn() } })); +const text = "1\n00:00:00,000 --> 00:00:01,000\nHello world"; +function doc() { + return documentSchema.parse({ + schemaVersion: 9, + project: { + id: "p", + title: "P", + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + primaryAssetId: "a", + }, + assets: [ + { id: "a", label: "Recording", originalPath: "/a.mp4", durationSec: 4, kind: "video" }, + { id: "b", label: "Voiceover", originalPath: "/b.wav", durationSec: 4, kind: "audio" }, + ], + timeline: { clips: [] }, + transcripts: [], + audioTracks: [{ id: "v", assetId: "b", kind: "voiceover", startMs: 0, endMs: 4000 }], + }); +} +function show() { + return render( + + + , + ); +} +function file(content = text) { + fireEvent.change(screen.getByLabelText("SRT file"), { + target: { files: [{ name: "example.srt", text: () => Promise.resolve(content) }] }, + }); +} +beforeEach(() => { + clearHistory(); + useProjectStore.setState({ projectId: "p", document: doc() }); + useTranscriptionStore.setState({ projectId: "p", jobs: {} }); + mocks.save.mockImplementation(async (document) => ({ success: true, document })); +}); +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); +it("requires an explicit asset and saves only that transcript with history and provenance", async () => { + show(); + expect(screen.getByRole("button", { name: "Import" })).toBeDisabled(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "b" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + await waitFor(() => expect(mocks.save).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(useProjectStore.getState().document?.transcripts).toHaveLength(1)); + expect(useProjectStore.getState().document?.transcripts[0].assetId).toBe("b"); + expect(useProjectStore.getState().document?.transcript).toBeNull(); + expect(past).toHaveLength(1); + expect(undo()).toBe(true); + expect(useProjectStore.getState().document?.transcripts).toHaveLength(0); + expect(redo()).toBe(true); + expect(useProjectStore.getState().document?.transcripts[0].importSource?.fileName).toBe( + "example.srt", + ); + expect(useProjectStore.getState().document?.timeline).toEqual(doc().timeline); +}); +it("validates the entire file before replacing existing text", async () => { + const d = doc(); + d.transcripts = [transcriptFromSrt("a", text, 4, "old.srt")]; + useProjectStore.setState({ document: d }); + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file("bad"); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + await screen.findByRole("alert"); + expect(mocks.save).not.toHaveBeenCalled(); + expect(useProjectStore.getState().document?.transcripts).toEqual(d.transcripts); +}); +it("asks to replace and rejects transcript changes while awaiting confirmation", async () => { + const d = doc(); + d.transcripts = [transcriptFromSrt("a", text, 4, "old.srt")]; + useProjectStore.setState({ document: d }); + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + const replace = await screen.findByRole("button", { name: "Replace transcript" }); + useProjectStore.setState({ + document: { ...d, transcripts: [transcriptFromSrt("a", text, 4, "new.srt")] }, + }); + fireEvent.click(replace); + await screen.findByRole("alert"); + expect(mocks.save).not.toHaveBeenCalled(); +}); +it("disables a queued transcription target", () => { + useTranscriptionStore.setState({ + jobs: { a: { status: "queued", language: "auto", manual: false } }, + }); + show(); + expect(screen.getByRole("option", { name: /Recording/ })).toBeDisabled(); +}); + +it("abandons a file read when the dialog unmounts", async () => { + let resolve!: (text: string) => void; + const view = show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + fireEvent.change(screen.getByLabelText("SRT file"), { + target: { + files: [ + { + name: "example.srt", + text: () => + new Promise((r) => { + resolve = r; + }), + }, + ], + }, + }); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + view.unmount(); + resolve(text); + await new Promise((r) => setTimeout(r, 0)); + expect(mocks.save).not.toHaveBeenCalled(); +}); +it.each(["project", "removed", "busy"])("refuses a stale %s after reading", async (change) => { + let resolve!: (text: string) => void; + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + fireEvent.change(screen.getByLabelText("SRT file"), { + target: { + files: [ + { + name: "example.srt", + text: () => + new Promise((r) => { + resolve = r; + }), + }, + ], + }, + }); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + const d = useProjectStore.getState().document!; + if (change === "project") + useProjectStore.setState({ + projectId: "other", + document: { ...d, project: { ...d.project, id: "other" } }, + }); + if (change === "removed") + useProjectStore.setState({ document: { ...d, assets: d.assets.filter((a) => a.id !== "a") } }); + if (change === "busy") + useTranscriptionStore.setState({ + jobs: { a: { status: "running", language: "auto", manual: false } }, + }); + resolve(text); + await screen.findByRole("alert"); + expect(mocks.save).not.toHaveBeenCalled(); +}); +it("reports failed saves without adding history or replacing text", async () => { + mocks.save.mockResolvedValue({ success: false, error: "disk full" }); + const before = useProjectStore.getState().document; + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Could not save"); + expect(past).toHaveLength(0); + expect(useProjectStore.getState().document).toBe(before); +}); +it("imports the primary transcript only after explicit replacement confirmation", async () => { + const d = doc(); + const old = transcriptFromSrt("a", text, 4, "old.srt"); + d.transcript = old; + d.transcripts = [old]; + useProjectStore.setState({ document: d }); + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + const replace = await screen.findByRole("button", { name: "Replace transcript" }); + expect(mocks.save).not.toHaveBeenCalled(); + fireEvent.click(replace); + await waitFor(() => expect(past).toHaveLength(1)); + const saved = useProjectStore.getState().document!; + expect(saved.transcript).toEqual(saved.transcripts[0]); + expect(saved.transcript?.importSource?.fileName).toBe("example.srt"); + expect(saved.assets).toEqual(d.assets); + expect(saved.audioTracks).toEqual(d.audioTracks); +}); diff --git a/src/components/ai-edition/ImportSrtDialog.tsx b/src/components/ai-edition/ImportSrtDialog.tsx new file mode 100644 index 0000000000..8e6b1548fb --- /dev/null +++ b/src/components/ai-edition/ImportSrtDialog.tsx @@ -0,0 +1,200 @@ +import { useEffect, useRef, useState } from "react"; +import { useScopedT } from "@/contexts/I18nContext"; +import { withTranscript } from "@/lib/ai-edition/document/transcript"; +import type { AxcutAsset, AxcutTranscript } from "@/lib/ai-edition/schema"; +import { useProjectStore } from "@/lib/ai-edition/store/projectStore"; +import { runTranscriptImport } from "@/lib/ai-edition/store/transcriptImport"; +import { useTranscriptionStore } from "@/lib/ai-edition/store/transcriptionStore"; +import { SrtImportError, transcriptFromSrt } from "@/lib/ai-edition/transcription/fromSrt"; +import { findAssetTranscript } from "@/lib/ai-edition/transcription/status"; +import { ModalShell } from "./Modals"; +import styles from "./NewEditorShell.module.css"; + +interface PendingImport { + transcript: AxcutTranscript; + previous: AxcutTranscript | null; + asset: AxcutAsset; + projectId: string; +} + +/** File input is user-granted text access; no filesystem IPC or HTML rendering. */ +export function ImportSrtDialog({ onClose }: { onClose: () => void }) { + const ts = useScopedT("settings"); + const tc = useScopedT("common"); + const document = useProjectStore((s) => s.document); + const jobs = useTranscriptionStore((s) => s.jobs); + const initialProject = useRef(document?.project.id); + const voiceovers = new Set( + document?.audioTracks.filter((t) => t.kind === "voiceover").map((t) => t.assetId), + ); + const assets = document?.assets.filter((a) => a.kind === "video" || voiceovers.has(a.id)) ?? []; + const [assetId, setAssetId] = useState(assets.length === 1 ? assets[0].id : ""); + const [file, setFile] = useState(null); + const [pending, setPending] = useState(null); + const [error, setError] = useState(""); + const [working, setWorking] = useState(false); + const generation = useRef(0); + useEffect( + () => () => { + generation.current++; + }, + [], + ); + const busy = (id: string) => { + const job = useTranscriptionStore.getState().jobs[id]; + return job?.status === "running" || job?.status === "queued"; + }; + const close = () => { + generation.current++; + onClose(); + }; + const valid = (p: PendingImport) => { + const current = useProjectStore.getState().document; + return ( + current?.project.id === p.projectId && + current.project.id === initialProject.current && + current.assets.find((a) => a.id === p.asset.id) === p.asset && + findAssetTranscript(current, p.asset.id) === p.previous && + !busy(p.asset.id) + ); + }; + const commit = async (p: PendingImport) => { + if (!valid(p)) { + setPending(null); + setError(ts("transcript.srt.stale")); + return; + } + const current = useProjectStore.getState().document!; + setWorking(true); + try { + const saved = await runTranscriptImport(p.projectId, p.asset.id, () => + useProjectStore + .getState() + .saveDocument(withTranscript(current, p.transcript), { history: true }), + ); + if (saved) close(); + else setError(ts("transcript.srt.saveFailed")); + } catch { + setError(ts("transcript.srt.saveFailed")); + } finally { + setWorking(false); + } + }; + const read = async () => { + const current = useProjectStore.getState().document; + const asset = current?.assets.find((a) => a.id === assetId); + if ( + !file || + !asset || + !current || + current.project.id !== initialProject.current || + busy(assetId) + ) { + setError(ts("transcript.srt.stale")); + return; + } + const p = { + asset, + projectId: current.project.id, + previous: findAssetTranscript(current, assetId), + }; + const token = ++generation.current; + setWorking(true); + setError(""); + try { + const text = await file.text(); + if (token !== generation.current) return; + const result = { + ...p, + transcript: transcriptFromSrt(assetId, text, asset.durationSec ?? 0, file.name), + }; + if (!valid(result)) { + setError(ts("transcript.srt.stale")); + return; + } + if (p.previous) setPending(result); + else await commit(result); + } catch (e) { + if (token !== generation.current) return; + setError( + e instanceof SrtImportError + ? ts("transcript.srt.validation", { + cue: e.cue, + line: e.line, + reason: ts(`transcript.srt.errors.${e.code}`), + }) + : ts("transcript.srt.readFailed"), + ); + } finally { + setWorking(false); + } + }; + return ( + + + + + } + > +

{ts("transcript.srt.sourceTime")}

+

{ts("transcript.srt.estimated")}

+ + + {pending ?

{ts("transcript.srt.replaceWarning", { name: pending.asset.label })}

: null} + {error ?

{error}

: null} +
+ ); +} diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx index 8cf35e98aa..6c0fee6c70 100644 --- a/src/components/ai-edition/RightPanes.tsx +++ b/src/components/ai-edition/RightPanes.tsx @@ -157,6 +157,7 @@ import { useClickSound } from "../../hooks/useClickSound"; import { useCanSegmentCamera } from "../../native/hooks/useSegmentationSupport"; import { CaptionsPane } from "./CaptionsPane"; import { ColorField } from "./ColorField"; +import { ImportSrtDialog } from "./ImportSrtDialog"; import { insertionsEnabled } from "./insertionsEnabled"; import styles from "./NewEditorShell.module.css"; import { useRecordedCursorTypes } from "./recordedCursorTypes"; @@ -948,6 +949,21 @@ export function TranscriptPane({ const silentMedia = blocked?.reason === "no-audio"; const transcriptionLabel = useTranscriptionLabel(); const [captionsOpen, setCaptionsOpen] = useState(false); + const [srtOpen, setSrtOpen] = useState(false); + const srtActions = ( + <> + + setCaptionsOpen(true)} /> + {srtOpen ? setSrtOpen(false)} /> : null} + + ); const paneBusyLabel = transcriptionBusyLabel( busyView ?? (isTranscribing ? { assetId: "", status: "running", phase: "loading-model" } : undefined), @@ -969,9 +985,12 @@ export function TranscriptPane({ title={ts("transcript.title")} icon={} helpText={helpText} - actions={ setCaptionsOpen(true)} />} + actions={srtActions} > {laneSwitch} + {transcripts.some((t) => t.importSource?.format === "srt") ? ( +

{ts("transcript.srt.estimated")}

+ ) : null}
} helpText={helpText} - actions={ setCaptionsOpen(true)} />} + actions={srtActions} > {laneSwitch} + {transcripts.some((t) => t.importSource?.format === "srt") ? ( +

{ts("transcript.srt.estimated")}

+ ) : null} {/* The gestures are invisible until tried: nothing on a plain word stream says * that double-click corrects and Backspace cuts. One muted line names them; the * ? popover above carries the long version (amber inserts, hover-bin restore). */} diff --git a/src/i18n/locales/ar/settings.json b/src/i18n/locales/ar/settings.json index 2e599890e4..d00b1d4f55 100644 --- a/src/i18n/locales/ar/settings.json +++ b/src/i18n/locales/ar/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "لا يوجد نص لهذا المقطع — افتح بطاقة الوسيط وأعد التوليد.", "editingHintDev": "انقر نقرًا مزدوجًا على كلمة لتصحيحها، واضغط Backspace لقطعها من الفيلم، واكتب بين كلمتين لإضافة كلمة.", "noAudio": "لا يحتوي هذا الملف على مسار صوتي", - "blankedWord": "مُفرَّغة" + "blankedWord": "مُفرَّغة", + "srt": { + "title": "استيراد SRT", + "import": "استيراد", + "replace": "استبدال النص", + "target": "الوسائط المستهدفة", + "chooseTarget": "اختر تسجيلاً أو تعليقاً صوتياً", + "file": "ملف SRT", + "busy": "جارٍ التفريغ", + "sourceTime": "توقيت الترجمة يخص الوسائط الأصلية قبل القص أو تغيير السرعة.", + "estimated": "توقيت الكلمات المستوردة تقديري؛ قد يكون التظليل والقص حسب الكلمات غير دقيق.", + "replaceWarning": "هل تريد استبدال نص {{name}}؟ يمكن التراجع عن ذلك.", + "stale": "تغير المشروع أو الوسائط أو النص، أو بدأ التفريغ. أعد فتح نافذة الاستيراد.", + "saveFailed": "تعذر حفظ النص. حاول مجدداً.", + "readFailed": "تعذرت قراءة ملف الترجمة.", + "validation": "المقطع {{cue}}، السطر {{line}}: {{reason}}", + "errors": { + "empty": "الملف لا يحتوي على ترجمة.", + "index": "يجب أن يكون رقم المقطع عدداً موجباً.", + "timestamp": "التنسيق المطلوب HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "يجب أن يأتي وقت النهاية بعد البداية.", + "bounds": "تتجاوز الترجمة مدة الوسائط، أو أن المدة غير معروفة.", + "markup": "يدعم النص العادي وعلامات b وi وu فقط.", + "overlap": "يجب ترتيب المقاطع دون تداخل.", + "text": "يجب أن يحتوي المقطع على نص." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/cs/settings.json b/src/i18n/locales/cs/settings.json index bdfc5bd6e3..1bab58bad4 100644 --- a/src/i18n/locales/cs/settings.json +++ b/src/i18n/locales/cs/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Pro tento klip není přepis. Otevřete kartu média a znovu generujte.", "editingHintDev": "Dvojklikem slovo opravte, Backspace ho vystřihne z filmu, psaním mezi dvěma slovy přidáte nové.", "noAudio": "Toto médium nemá zvukovou stopu", - "blankedWord": "vynecháno" + "blankedWord": "vynecháno", + "srt": { + "title": "Importovat SRT", + "import": "Importovat", + "replace": "Nahradit přepis", + "target": "Cílové médium", + "chooseTarget": "Vyberte záznam nebo komentář", + "file": "Soubor SRT", + "busy": "Probíhá přepis", + "sourceTime": "Časy titulků odkazují na původní médium před střihy a změnami rychlosti.", + "estimated": "Časy importovaných slov jsou odhadnuté. Zvýraznění a střih podle slov mohou být nepřesné.", + "replaceWarning": "Nahradit přepis pro {{name}}? Tuto akci lze vrátit.", + "stale": "Projekt, médium nebo přepis se změnil, případně začal přepis. Otevřete import znovu.", + "saveFailed": "Přepis nelze uložit. Zkuste to znovu.", + "readFailed": "Soubor titulků nelze přečíst.", + "validation": "Titulek {{cue}}, řádek {{line}}: {{reason}}", + "errors": { + "empty": "Soubor neobsahuje titulky.", + "index": "Očekává se kladné číselné pořadí titulku.", + "timestamp": "Očekává se HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "Konec musí být později než začátek.", + "bounds": "Titulek překračuje délku média nebo délka není známá.", + "markup": "Podporován je prostý text a značky b, i, u.", + "overlap": "Titulky musí být seřazené a nesmí se překrývat.", + "text": "Titulek musí obsahovat text." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/de/settings.json b/src/i18n/locales/de/settings.json index 61707f28eb..27cf2de832 100644 --- a/src/i18n/locales/de/settings.json +++ b/src/i18n/locales/de/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Kein Transkript für diesen Clip — öffne die Asset-Karte und erzeuge es neu.", "editingHintDev": "Doppelklick auf ein Wort korrigiert es, Backspace schneidet es aus dem Film, Tippen zwischen zwei Wörtern fügt eines hinzu.", "noAudio": "Dieses Medium hat keine Audiospur", - "blankedWord": "geleert" + "blankedWord": "geleert", + "srt": { + "title": "SRT importieren", + "import": "Importieren", + "replace": "Transkript ersetzen", + "target": "Zielmedium", + "chooseTarget": "Aufnahme oder Sprachaufnahme wählen", + "file": "SRT-Datei", + "busy": "Transkription läuft", + "sourceTime": "Untertitelzeiten beziehen sich auf das Originalmedium vor Schnitten und Tempoänderungen.", + "estimated": "Wortzeiten importierter Untertitel sind geschätzt. Worthervorhebung und wortbasierte Schnitte können ungenau sein.", + "replaceWarning": "Transkript für {{name}} ersetzen? Dies kann rückgängig gemacht werden.", + "stale": "Projekt, Medium oder Transkript wurde geändert oder eine Transkription gestartet. Importdialog erneut öffnen.", + "saveFailed": "Transkript konnte nicht gespeichert werden. Erneut versuchen.", + "readFailed": "Untertiteldatei konnte nicht gelesen werden.", + "validation": "Untertitel {{cue}}, Zeile {{line}}: {{reason}}", + "errors": { + "empty": "Die Datei enthält keine Untertitel.", + "index": "Eine positive numerische Untertitelnummer wird erwartet.", + "timestamp": "Erwartet: HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "Die Endzeit muss nach der Startzeit liegen.", + "bounds": "Der Untertitel überschreitet die Mediendauer oder die Dauer ist unbekannt.", + "markup": "Nur Klartext und die Formatierungstags b, i, u werden unterstützt.", + "overlap": "Untertitel müssen geordnet sein und dürfen sich nicht überschneiden.", + "text": "Der Untertitel muss Text enthalten." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.json index 122ff48143..a1d640aeb8 100644 --- a/src/i18n/locales/en/settings.json +++ b/src/i18n/locales/en/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "No transcript for this clip — open the asset card and regenerate.", "editingHintDev": "Double-click a word to correct it, Backspace cuts it from the film, type between two words to add one.", "noAudio": "This media has no audio track", - "blankedWord": "blanked" + "blankedWord": "blanked", + "srt": { + "title": "Import SRT", + "import": "Import", + "replace": "Replace transcript", + "target": "Target media", + "chooseTarget": "Choose a recording or voiceover", + "file": "SRT file", + "busy": "Transcribing", + "sourceTime": "Subtitle timestamps refer to the original media, before timeline cuts or speed changes.", + "estimated": "Imported subtitle word timings are estimated. Word highlighting and word-based cuts may be approximate.", + "replaceWarning": "Replace the existing transcript for {{name}}? This can be undone.", + "stale": "The project, media or transcript changed, or transcription started. Close and reopen the import dialog.", + "saveFailed": "Could not save the transcript. Try again.", + "readFailed": "Could not read the subtitle file.", + "validation": "Cue {{cue}}, line {{line}}: {{reason}}", + "errors": { + "empty": "The file contains no subtitles.", + "index": "Expected a positive numeric cue index.", + "timestamp": "Expected HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "The end time must be after the start time.", + "bounds": "The subtitle exceeds the source media duration, or its duration is unknown.", + "markup": "Only plain text and b, i, u formatting tags are supported.", + "overlap": "Cues must be ordered and must not overlap.", + "text": "The cue must contain text." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/es/settings.json b/src/i18n/locales/es/settings.json index 7f6ae74928..c7aef1df04 100644 --- a/src/i18n/locales/es/settings.json +++ b/src/i18n/locales/es/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Este clip no tiene transcripción: abre la ficha del recurso y vuelve a generarla.", "editingHintDev": "Haz doble clic en una palabra para corregirla, Retroceso la corta del vídeo, escribe entre dos palabras para añadir una.", "noAudio": "Este medio no tiene pista de audio", - "blankedWord": "vaciada" + "blankedWord": "vaciada", + "srt": { + "title": "Importar SRT", + "import": "Importar", + "replace": "Reemplazar transcripción", + "target": "Medio de destino", + "chooseTarget": "Elige una grabación o voz en off", + "file": "Archivo SRT", + "busy": "Transcribiendo", + "sourceTime": "Los tiempos se refieren al medio original, antes de cortes o cambios de velocidad.", + "estimated": "Los tiempos de palabras importadas son estimados. El resaltado y los cortes por palabras pueden ser imprecisos.", + "replaceWarning": "¿Reemplazar la transcripción de {{name}}? Se puede deshacer.", + "stale": "El proyecto, el medio o la transcripción cambió, o comenzó una transcripción. Vuelve a abrir la importación.", + "saveFailed": "No se pudo guardar. Inténtalo de nuevo.", + "readFailed": "No se pudo leer el archivo de subtítulos.", + "validation": "Subtítulo {{cue}}, línea {{line}}: {{reason}}", + "errors": { + "empty": "El archivo no contiene subtítulos.", + "index": "Se esperaba un índice numérico positivo.", + "timestamp": "Se esperaba HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "El final debe ser posterior al inicio.", + "bounds": "El subtítulo supera la duración del medio o su duración es desconocida.", + "markup": "Solo se admiten texto plano y etiquetas b, i, u.", + "overlap": "Los subtítulos deben estar ordenados y no solaparse.", + "text": "El subtítulo debe contener texto." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/fr/settings.json b/src/i18n/locales/fr/settings.json index 8cee3e8460..2dc1297ab7 100644 --- a/src/i18n/locales/fr/settings.json +++ b/src/i18n/locales/fr/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Aucune transcription pour ce clip — ouvrez la fiche du média et relancez la génération.", "editingHintDev": "Double-cliquez sur un mot pour le corriger, Retour arrière le coupe du film, tapez entre deux mots pour en ajouter un.", "noAudio": "Ce média n'a pas de piste audio", - "blankedWord": "vidé" + "blankedWord": "vidé", + "srt": { + "title": "Importer un SRT", + "import": "Importer", + "replace": "Remplacer la transcription", + "target": "Média cible", + "chooseTarget": "Choisir un enregistrement ou une voix off", + "file": "Fichier SRT", + "busy": "Transcription en cours", + "sourceTime": "Les horodatages concernent le média original, avant les coupes et changements de vitesse.", + "estimated": "Les temps des mots importés sont estimés. Le surlignage et les coupes par mot peuvent être approximatifs.", + "replaceWarning": "Remplacer la transcription de {{name}} ? Cette action peut être annulée.", + "stale": "Le projet, le média ou la transcription a changé, ou une transcription a démarré. Rouvrez la fenêtre d’import.", + "saveFailed": "Impossible d’enregistrer la transcription. Réessayez.", + "readFailed": "Impossible de lire le fichier de sous-titres.", + "validation": "Sous-titre {{cue}}, ligne {{line}} : {{reason}}", + "errors": { + "empty": "Le fichier ne contient aucun sous-titre.", + "index": "Un numéro de sous-titre positif est attendu.", + "timestamp": "Format attendu : HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "La fin doit être après le début.", + "bounds": "Le sous-titre dépasse la durée du média, ou sa durée est inconnue.", + "markup": "Seuls le texte brut et les balises b, i, u sont pris en charge.", + "overlap": "Les sous-titres doivent être ordonnés sans chevauchement.", + "text": "Le sous-titre doit contenir du texte." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/it/settings.json b/src/i18n/locales/it/settings.json index 977040db8d..bef94cee59 100644 --- a/src/i18n/locales/it/settings.json +++ b/src/i18n/locales/it/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Nessuna trascrizione per questo clip: apri la scheda della risorsa e rigenerala.", "editingHintDev": "Fai doppio clic su una parola per correggerla, Backspace la taglia dal video, scrivi tra due parole per aggiungerne una.", "noAudio": "Questo contenuto non ha una traccia audio", - "blankedWord": "svuotata" + "blankedWord": "svuotata", + "srt": { + "title": "Importa SRT", + "import": "Importa", + "replace": "Sostituisci trascrizione", + "target": "Media di destinazione", + "chooseTarget": "Scegli una registrazione o voce fuori campo", + "file": "File SRT", + "busy": "Trascrizione in corso", + "sourceTime": "I tempi dei sottotitoli si riferiscono al media originale, prima di tagli o cambi di velocità.", + "estimated": "I tempi delle parole importate sono stimati. Evidenziazione e tagli per parola possono essere approssimativi.", + "replaceWarning": "Sostituire la trascrizione di {{name}}? Puoi annullare questa azione.", + "stale": "Il progetto, il media o la trascrizione è cambiato, oppure è iniziata una trascrizione. Riapri l’importazione.", + "saveFailed": "Impossibile salvare la trascrizione. Riprova.", + "readFailed": "Impossibile leggere il file dei sottotitoli.", + "validation": "Sottotitolo {{cue}}, riga {{line}}: {{reason}}", + "errors": { + "empty": "Il file non contiene sottotitoli.", + "index": "È richiesto un indice numerico positivo.", + "timestamp": "Formato richiesto: HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "La fine deve essere successiva all’inizio.", + "bounds": "Il sottotitolo supera la durata del media o la durata è sconosciuta.", + "markup": "Sono supportati solo testo semplice e tag b, i, u.", + "overlap": "I sottotitoli devono essere ordinati e non sovrapporsi.", + "text": "Il sottotitolo deve contenere testo." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/ja-JP/settings.json b/src/i18n/locales/ja-JP/settings.json index ec739e70ee..f92d842819 100644 --- a/src/i18n/locales/ja-JP/settings.json +++ b/src/i18n/locales/ja-JP/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "このクリップには文字起こしがありません。アセットカードを開いて再生成してください。", "editingHintDev": "ダブルクリックで単語を修正、Backspace で映像からカット、2つの単語の間に入力して新しい単語を追加。", "noAudio": "このメディアには音声トラックがありません", - "blankedWord": "空欄" + "blankedWord": "空欄", + "srt": { + "title": "SRTをインポート", + "import": "インポート", + "replace": "文字起こしを置換", + "target": "対象メディア", + "chooseTarget": "録画またはナレーションを選択", + "file": "SRTファイル", + "busy": "文字起こし中", + "sourceTime": "字幕の時刻は、カットや速度変更前の元メディアを基準にします。", + "estimated": "インポートした字幕の単語時刻は推定値です。単語の強調表示や単語単位のカットは正確でない場合があります。", + "replaceWarning": "{{name}}の文字起こしを置き換えますか?元に戻せます。", + "stale": "プロジェクト、メディア、文字起こしが変更されたか、文字起こしが開始されました。インポート画面を開き直してください。", + "saveFailed": "文字起こしを保存できませんでした。再試行してください。", + "readFailed": "字幕ファイルを読み込めませんでした。", + "validation": "字幕{{cue}}、行{{line}}:{{reason}}", + "errors": { + "empty": "ファイルに字幕がありません。", + "index": "字幕番号は正の整数で指定してください。", + "timestamp": "HH:MM:SS,mmm --> HH:MM:SS,mmm形式で指定してください。", + "duration": "終了時刻は開始時刻より後にしてください。", + "bounds": "字幕が元メディアの長さを超えているか、長さが不明です。", + "markup": "プレーンテキストとb、i、uタグのみ対応しています。", + "overlap": "字幕は時刻順で、重ならないようにしてください。", + "text": "字幕にテキストが必要です。" + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/ko-KR/settings.json b/src/i18n/locales/ko-KR/settings.json index 12c13cd7f4..7662d05393 100644 --- a/src/i18n/locales/ko-KR/settings.json +++ b/src/i18n/locales/ko-KR/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "이 클립에는 전사가 없습니다. 에셋 카드를 열고 다시 생성하세요.", "editingHintDev": "단어를 더블 클릭해 수정하고, Backspace로 영상에서 잘라내고, 두 단어 사이에 입력해 새 단어를 추가하세요.", "noAudio": "이 미디어에는 오디오 트랙이 없습니다", - "blankedWord": "비움" + "blankedWord": "비움", + "srt": { + "title": "SRT 가져오기", + "import": "가져오기", + "replace": "대본 바꾸기", + "target": "대상 미디어", + "chooseTarget": "녹화 또는 음성 해설 선택", + "file": "SRT 파일", + "busy": "대본 생성 중", + "sourceTime": "자막 시간은 자르기나 속도 변경 전 원본 미디어 기준입니다.", + "estimated": "가져온 자막의 단어 시간은 추정값입니다. 단어 강조와 단어 단위 자르기가 부정확할 수 있습니다.", + "replaceWarning": "{{name}}의 대본을 바꾸시겠습니까? 실행 취소할 수 있습니다.", + "stale": "프로젝트, 미디어 또는 대본이 변경되었거나 대본 생성이 시작되었습니다. 가져오기 창을 다시 여세요.", + "saveFailed": "대본을 저장할 수 없습니다. 다시 시도하세요.", + "readFailed": "자막 파일을 읽을 수 없습니다.", + "validation": "자막 {{cue}}, 줄 {{line}}: {{reason}}", + "errors": { + "empty": "파일에 자막이 없습니다.", + "index": "양의 숫자로 된 자막 번호가 필요합니다.", + "timestamp": "HH:MM:SS,mmm --> HH:MM:SS,mmm 형식이 필요합니다.", + "duration": "종료 시간은 시작 시간보다 뒤여야 합니다.", + "bounds": "자막이 원본 미디어 길이를 초과하거나 길이를 알 수 없습니다.", + "markup": "일반 텍스트와 b, i, u 태그만 지원합니다.", + "overlap": "자막은 시간순이어야 하며 겹치면 안 됩니다.", + "text": "자막에 텍스트가 있어야 합니다." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/pt-BR/settings.json b/src/i18n/locales/pt-BR/settings.json index 65f8c2761a..0535c64063 100644 --- a/src/i18n/locales/pt-BR/settings.json +++ b/src/i18n/locales/pt-BR/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Sem transcrição para este clipe — abra o cartão do recurso e gere novamente.", "editingHintDev": "Clique duas vezes em uma palavra para corrigi-la, Backspace a corta do vídeo, digite entre duas palavras para adicionar uma.", "noAudio": "Esta mídia não tem faixa de áudio", - "blankedWord": "apagada" + "blankedWord": "apagada", + "srt": { + "title": "Importar SRT", + "import": "Importar", + "replace": "Substituir transcrição", + "target": "Mídia de destino", + "chooseTarget": "Escolha uma gravação ou narração", + "file": "Arquivo SRT", + "busy": "Transcrevendo", + "sourceTime": "Os tempos das legendas se referem à mídia original, antes de cortes ou mudanças de velocidade.", + "estimated": "Os tempos das palavras importadas são estimados. O destaque e os cortes por palavra podem ser imprecisos.", + "replaceWarning": "Substituir a transcrição de {{name}}? Esta ação pode ser desfeita.", + "stale": "O projeto, a mídia ou a transcrição mudou, ou uma transcrição foi iniciada. Reabra a importação.", + "saveFailed": "Não foi possível salvar a transcrição. Tente novamente.", + "readFailed": "Não foi possível ler o arquivo de legendas.", + "validation": "Legenda {{cue}}, linha {{line}}: {{reason}}", + "errors": { + "empty": "O arquivo não contém legendas.", + "index": "Era esperado um índice numérico positivo.", + "timestamp": "Formato esperado: HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "O fim deve ser posterior ao início.", + "bounds": "A legenda excede a duração da mídia ou a duração é desconhecida.", + "markup": "Apenas texto simples e tags b, i, u são aceitos.", + "overlap": "As legendas devem estar ordenadas e não se sobrepor.", + "text": "A legenda deve conter texto." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/ru/settings.json b/src/i18n/locales/ru/settings.json index d548578b61..bf83f9c232 100644 --- a/src/i18n/locales/ru/settings.json +++ b/src/i18n/locales/ru/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Для этого клипа нет расшифровки — откройте карточку файла и создайте её заново.", "editingHintDev": "Дважды щёлкните слово, чтобы исправить его, Backspace вырезает его из фильма, напечатайте между двумя словами, чтобы добавить одно.", "noAudio": "В этом медиафайле нет аудиодорожки", - "blankedWord": "очищено" + "blankedWord": "очищено", + "srt": { + "title": "Импорт SRT", + "import": "Импортировать", + "replace": "Заменить расшифровку", + "target": "Целевой медиафайл", + "chooseTarget": "Выберите запись или озвучку", + "file": "Файл SRT", + "busy": "Расшифровка", + "sourceTime": "Время субтитров относится к исходному медиафайлу до обрезки и изменения скорости.", + "estimated": "Время импортированных слов приблизительное. Подсветка и обрезка по словам могут быть неточными.", + "replaceWarning": "Заменить расшифровку для {{name}}? Это действие можно отменить.", + "stale": "Проект, медиафайл или расшифровка изменились либо начата расшифровка. Откройте импорт заново.", + "saveFailed": "Не удалось сохранить расшифровку. Повторите попытку.", + "readFailed": "Не удалось прочитать файл субтитров.", + "validation": "Субтитр {{cue}}, строка {{line}}: {{reason}}", + "errors": { + "empty": "В файле нет субтитров.", + "index": "Ожидается положительный числовой номер субтитра.", + "timestamp": "Ожидается HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "Время окончания должно быть позже начала.", + "bounds": "Субтитр выходит за длительность медиафайла либо длительность неизвестна.", + "markup": "Поддерживаются только обычный текст и теги b, i, u.", + "overlap": "Субтитры должны идти по порядку и не пересекаться.", + "text": "Субтитр должен содержать текст." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/tr/settings.json b/src/i18n/locales/tr/settings.json index 26842ec8a0..18fa49a741 100644 --- a/src/i18n/locales/tr/settings.json +++ b/src/i18n/locales/tr/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Bu klip için döküm yok — medya kartını açıp yeniden oluşturun.", "editingHintDev": "Bir kelimeye çift tıklayarak düzeltin, Backspace onu videodan keser, iki kelimenin arasına yazarak yeni kelime ekleyin.", "noAudio": "Bu medyada ses parçası yok", - "blankedWord": "boşaltıldı" + "blankedWord": "boşaltıldı", + "srt": { + "title": "SRT içe aktar", + "import": "İçe aktar", + "replace": "Dökümü değiştir", + "target": "Hedef medya", + "chooseTarget": "Bir kayıt veya seslendirme seçin", + "file": "SRT dosyası", + "busy": "Döküm hazırlanıyor", + "sourceTime": "Altyazı zamanları, kesim ve hız değişikliklerinden önceki özgün medyaya aittir.", + "estimated": "İçe aktarılan sözcük zamanları tahminidir. Sözcük vurguları ve sözcük tabanlı kesimler kesin olmayabilir.", + "replaceWarning": "{{name}} dökümü değiştirilsin mi? Bu işlem geri alınabilir.", + "stale": "Proje, medya veya döküm değişti ya da döküm başladı. İçe aktarma penceresini yeniden açın.", + "saveFailed": "Döküm kaydedilemedi. Yeniden deneyin.", + "readFailed": "Altyazı dosyası okunamadı.", + "validation": "Altyazı {{cue}}, satır {{line}}: {{reason}}", + "errors": { + "empty": "Dosyada altyazı yok.", + "index": "Pozitif sayısal altyazı numarası bekleniyor.", + "timestamp": "HH:MM:SS,mmm --> HH:MM:SS,mmm biçimi bekleniyor.", + "duration": "Bitiş zamanı başlangıçtan sonra olmalıdır.", + "bounds": "Altyazı medya süresini aşıyor veya süre bilinmiyor.", + "markup": "Yalnızca düz metin ve b, i, u etiketleri desteklenir.", + "overlap": "Altyazılar sıralı olmalı ve çakışmamalıdır.", + "text": "Altyazı metin içermelidir." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/vi/settings.json b/src/i18n/locales/vi/settings.json index ff225df50d..06d421a8d4 100644 --- a/src/i18n/locales/vi/settings.json +++ b/src/i18n/locales/vi/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Clip này chưa có bản chép lời — mở thẻ tài nguyên và tạo lại.", "editingHintDev": "Nhấp đúp vào một từ để sửa nó, Backspace cắt nó khỏi video, gõ giữa hai từ để thêm một từ mới.", "noAudio": "Media này không có bản âm thanh", - "blankedWord": "đã xoá" + "blankedWord": "đã xoá", + "srt": { + "title": "Nhập SRT", + "import": "Nhập", + "replace": "Thay bản chép lời", + "target": "Tệp phương tiện đích", + "chooseTarget": "Chọn bản ghi hoặc lời thuyết minh", + "file": "Tệp SRT", + "busy": "Đang chép lời", + "sourceTime": "Mốc thời gian phụ đề dựa trên tệp gốc, trước khi cắt hoặc thay đổi tốc độ.", + "estimated": "Thời gian của từng từ được nhập là ước tính. Tô sáng và cắt theo từ có thể không chính xác.", + "replaceWarning": "Thay bản chép lời của {{name}}? Có thể hoàn tác thao tác này.", + "stale": "Dự án, phương tiện hoặc bản chép lời đã thay đổi, hoặc quá trình chép lời đã bắt đầu. Hãy mở lại cửa sổ nhập.", + "saveFailed": "Không thể lưu bản chép lời. Hãy thử lại.", + "readFailed": "Không thể đọc tệp phụ đề.", + "validation": "Phụ đề {{cue}}, dòng {{line}}: {{reason}}", + "errors": { + "empty": "Tệp không chứa phụ đề.", + "index": "Cần số thứ tự phụ đề là số nguyên dương.", + "timestamp": "Cần định dạng HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "Thời điểm kết thúc phải sau thời điểm bắt đầu.", + "bounds": "Phụ đề vượt quá thời lượng nguồn hoặc chưa biết thời lượng.", + "markup": "Chỉ hỗ trợ văn bản thuần và thẻ b, i, u.", + "overlap": "Phụ đề phải đúng thứ tự và không chồng lấn.", + "text": "Phụ đề phải có nội dung." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/zh-CN/settings.json b/src/i18n/locales/zh-CN/settings.json index 47a62d2ff3..fa07e0a6aa 100644 --- a/src/i18n/locales/zh-CN/settings.json +++ b/src/i18n/locales/zh-CN/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "该片段没有转录 — 请打开素材卡片并重新生成。", "editingHintDev": "双击单词即可修正,Backspace 将其从影片中剪掉,在两个单词之间输入即可添加新词。", "noAudio": "此媒体没有音频轨道", - "blankedWord": "已清空" + "blankedWord": "已清空", + "srt": { + "title": "导入 SRT", + "import": "导入", + "replace": "替换转录", + "target": "目标媒体", + "chooseTarget": "选择录制或配音媒体", + "file": "SRT 文件", + "busy": "正在转录", + "sourceTime": "字幕时间以原始媒体为准,不受时间线裁剪或变速影响。", + "estimated": "导入字幕的词级时间为估算值,逐词高亮和按词裁剪可能不精确。", + "replaceWarning": "替换 {{name}} 的现有转录?此操作可以撤销。", + "stale": "项目、媒体或转录已更改,或转录任务已开始。请关闭并重新打开导入窗口。", + "saveFailed": "无法保存转录,请重试。", + "readFailed": "无法读取字幕文件。", + "validation": "第 {{cue}} 条字幕,第 {{line}} 行:{{reason}}", + "errors": { + "empty": "文件中没有字幕。", + "index": "字幕序号必须是正整数。", + "timestamp": "时间格式应为 HH:MM:SS,mmm --> HH:MM:SS,mmm。", + "duration": "结束时间必须晚于开始时间。", + "bounds": "字幕超过原始媒体时长,或媒体时长未知。", + "markup": "仅支持纯文本和 b、i、u 格式标签。", + "overlap": "字幕必须按时间排序,且不能重叠。", + "text": "字幕内容不能为空。" + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/zh-TW/settings.json b/src/i18n/locales/zh-TW/settings.json index 9725a48f69..e61626739d 100644 --- a/src/i18n/locales/zh-TW/settings.json +++ b/src/i18n/locales/zh-TW/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "此片段沒有逐字稿 — 請開啟素材卡片並重新產生。", "editingHintDev": "雙擊單字即可修正,Backspace 將其從影片中剪掉,在兩個單字之間輸入即可新增新詞。", "noAudio": "此媒體沒有音訊軌道", - "blankedWord": "已清空" + "blankedWord": "已清空", + "srt": { + "title": "匯入 SRT", + "import": "匯入", + "replace": "取代轉錄", + "target": "目標媒體", + "chooseTarget": "選擇錄製或配音媒體", + "file": "SRT 檔案", + "busy": "正在轉錄", + "sourceTime": "字幕時間以原始媒體為準,不受時間軸裁剪或變速影響。", + "estimated": "匯入字幕的逐字時間為估計值,逐字反白和按字裁剪可能不精確。", + "replaceWarning": "取代 {{name}} 的現有轉錄?此操作可以復原。", + "stale": "專案、媒體或轉錄已變更,或轉錄工作已開始。請關閉並重新開啟匯入視窗。", + "saveFailed": "無法儲存轉錄,請重試。", + "readFailed": "無法讀取字幕檔案。", + "validation": "第 {{cue}} 條字幕,第 {{line}} 行:{{reason}}", + "errors": { + "empty": "檔案中沒有字幕。", + "index": "字幕序號必須是正整數。", + "timestamp": "時間格式應為 HH:MM:SS,mmm --> HH:MM:SS,mmm。", + "duration": "結束時間必須晚於開始時間。", + "bounds": "字幕超過原始媒體長度,或媒體長度未知。", + "markup": "僅支援純文字和 b、i、u 格式標籤。", + "overlap": "字幕必須按時間排序,且不能重疊。", + "text": "字幕內容不能為空。" + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/lib/ai-edition/captions/cues.ts b/src/lib/ai-edition/captions/cues.ts index bde765a465..d53e2a293e 100644 --- a/src/lib/ai-edition/captions/cues.ts +++ b/src/lib/ai-edition/captions/cues.ts @@ -103,6 +103,24 @@ export function captionLinesForAsset( settings: CaptionSettings, translations: CaptionTranslations, ): CaptionSegment[] { + // External cues are authored boundaries, including intentional repeated lines. + if (transcript.importSource?.format === "srt") { + return transcript.segments.flatMap((segment) => { + const isolated = { + ...transcript, + importSource: undefined, + segments: [segment], + words: transcript.words.filter((word) => segment.wordIds.includes(word.id)), + }; + return captionLinesForAsset(isolated, settings, translations) + .map((line) => ({ + ...line, + startSec: Math.max(segment.startSec, line.startSec), + endSec: Math.min(segment.endSec, line.endSec), + })) + .filter((line) => line.endSec > line.startSec); + }); + } const minWords = settings.minWordsPerLine; const maxWords = settings.maxWordsPerLine; diff --git a/src/lib/ai-edition/captions/translations.ts b/src/lib/ai-edition/captions/translations.ts index 07abd1efbc..c0f8b07448 100644 --- a/src/lib/ai-edition/captions/translations.ts +++ b/src/lib/ai-edition/captions/translations.ts @@ -200,7 +200,10 @@ export function captionTranslationUnits(transcript: AxcutTranscript): CaptionTra continue; } - if (segment.startSec - current.endSec >= UNIT_BREAK_GAP_SEC) { + if ( + transcript.importSource?.format === "srt" || + segment.startSec - current.endSec >= UNIT_BREAK_GAP_SEC + ) { flush(); current = { id: unitKey(segment.id), diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.ts index e9bf15f1f8..6c1a4589e2 100644 --- a/src/lib/ai-edition/schema/index.ts +++ b/src/lib/ai-edition/schema/index.ts @@ -109,6 +109,9 @@ export const transcriptSegmentSchema = z }); export const transcriptSchema = z.object({ + importSource: z + .object({ format: z.literal("srt"), fileName: z.string(), wordTiming: z.literal("estimated") }) + .optional(), assetId: z.string().min(1), language: z.string().min(1), sourceDslPath: z.string().optional(), diff --git a/src/lib/ai-edition/store/documentWriteAudit.test.ts b/src/lib/ai-edition/store/documentWriteAudit.test.ts index a27d74ef17..ac194e1c3a 100644 --- a/src/lib/ai-edition/store/documentWriteAudit.test.ts +++ b/src/lib/ai-edition/store/documentWriteAudit.test.ts @@ -111,6 +111,9 @@ const WRITER_NAMES = { // --------------------------------------------------------------------------- const DECLARED: WritePath[] = [ + // A confirmed SRT import replaces one asset transcript in one undoable edit. + w("src/components/ai-edition/ImportSrtDialog.tsx", "commit", "save", "gesture"), + // Dropping the legacy auto-caption annotations is a button in the captions pane. w( "src/components/ai-edition/CaptionsPane.tsx", diff --git a/src/lib/ai-edition/store/transcriptImport.test.ts b/src/lib/ai-edition/store/transcriptImport.test.ts new file mode 100644 index 0000000000..7f7ee02d48 --- /dev/null +++ b/src/lib/ai-edition/store/transcriptImport.test.ts @@ -0,0 +1,37 @@ +import { expect, it } from "vitest"; +import { + runTranscriptImport, + transcriptImportPending, + waitForTranscriptImport, +} from "./transcriptImport"; + +it("holds the asset reservation until save settles, releasing failures too", async () => { + let finish!: () => void; + const work = runTranscriptImport( + "p", + "a", + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + expect(transcriptImportPending("p", "a")).toBe(true); + expect(transcriptImportPending("other", "a")).toBe(false); + let released = false; + const wait = waitForTranscriptImport("p", "a").then(() => { + released = true; + }); + await Promise.resolve(); + expect(released).toBe(false); + finish(); + await work; + await wait; + expect(released).toBe(true); + expect(transcriptImportPending("p", "a")).toBe(false); + await expect( + runTranscriptImport("p", "a", async () => { + throw new Error("save"); + }), + ).rejects.toThrow("save"); + expect(transcriptImportPending("p", "a")).toBe(false); +}); diff --git a/src/lib/ai-edition/store/transcriptImport.ts b/src/lib/ai-edition/store/transcriptImport.ts new file mode 100644 index 0000000000..f8358931b7 --- /dev/null +++ b/src/lib/ai-edition/store/transcriptImport.ts @@ -0,0 +1,33 @@ +// Keep the automatic speech queue from starting while an imported transcript is saving. +// Scoped to project + asset so an old project's disk write cannot block a new project. +const pending = new Map>>(); +export function transcriptImportPending(projectId: string, assetId: string): boolean { + return pending.get(projectId)?.has(assetId) ?? false; +} +export async function waitForTranscriptImport(projectId: string, assetId: string): Promise { + await pending.get(projectId)?.get(assetId); +} +export async function runTranscriptImport( + projectId: string, + assetId: string, + save: () => Promise, +): Promise { + let release!: () => void; + const done = new Promise((resolve) => { + release = resolve; + }); + let assets = pending.get(projectId); + if (!assets) { + assets = new Map(); + pending.set(projectId, assets); + } + if (assets.has(assetId)) throw new Error("Transcript import already saving"); + assets.set(assetId, done); + try { + return await save(); + } finally { + assets.delete(assetId); + if (!assets.size) pending.delete(projectId); + release(); + } +} diff --git a/src/lib/ai-edition/store/transcriptionStore.ts b/src/lib/ai-edition/store/transcriptionStore.ts index 341bd72f80..558f42d5a7 100644 --- a/src/lib/ai-edition/store/transcriptionStore.ts +++ b/src/lib/ai-edition/store/transcriptionStore.ts @@ -47,6 +47,7 @@ import { withTranscriptionFailure, } from "../transcription/status"; import { useProjectStore } from "./projectStore"; +import { transcriptImportPending, waitForTranscriptImport } from "./transcriptImport"; export interface TranscriptionJob { status: "queued" | "running" | "failed"; @@ -139,7 +140,7 @@ export const useTranscriptionStore = create((set, get) => ({ if (hasLocalSttEngine()) { for (const asset of document.assets) { - if (jobs[asset.id]) continue; + if (jobs[asset.id] || transcriptImportPending(document.project.id, asset.id)) continue; if (findAssetTranscript(document, asset.id)) continue; if (asset.transcriptionFailure) continue; // Music is not speech, and finding that out costs a whole inference pass — @@ -156,7 +157,12 @@ export const useTranscriptionStore = create((set, get) => ({ } }, - request(assetId, language = "auto") { + async request(assetId, language = "auto") { + const importProject = useProjectStore.getState().document?.project.id; + if (importProject && transcriptImportPending(importProject, assetId)) { + await waitForTranscriptImport(importProject, assetId); + if (useProjectStore.getState().document?.project.id !== importProject) return; + } // A manual run can be the first thing that happens in a project (the // auto pass is off without a local engine), so adopt the loaded project // before queueing — `runJob` refuses to write into a document the queue diff --git a/src/lib/ai-edition/transcription/fromSrt.test.ts b/src/lib/ai-edition/transcription/fromSrt.test.ts new file mode 100644 index 0000000000..9277d2fb49 --- /dev/null +++ b/src/lib/ai-edition/transcription/fromSrt.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import { transcriptSchema } from "../schema"; +import { SrtImportError, transcriptFromSrt } from "./fromSrt"; + +describe("SRT import", () => { + it("preserves cues and provenance through schema serialization", () => { + const t = transcriptFromSrt( + "a", + "\uFEFF1\r\n00:00:01,000 --> 00:00:02,000\r\nHello 世界\r\nnext line\r\n\r\n2\r\n00:00:02,010 --> 00:00:03,000\r\nAgain", + 4, + "captions.srt", + ); + expect(t.segments.map((s) => s.text)).toEqual(["Hello 世界\nnext line", "Again"]); + expect(t.words).toHaveLength(5); + const serialized = JSON.stringify(t); + expect(transcriptSchema.parse(JSON.parse(serialized)).importSource).toEqual({ + format: "srt", + fileName: "captions.srt", + wordTiming: "estimated", + }); + expect(t.words[0].id).not.toBe("word_1"); + }); + it.each([ + ["", "empty"], + ["1\n00:00:00,000 --> 00:00:04,001\nx", "bounds"], + ["x\n00:00:00,000 --> 00:00:01,000\nx", "index"], + ["1\n00:60:00,000 --> 00:00:01,000\nx", "timestamp"], + ["1\n00:00:00,000 -> 00:00:01,000\nx", "timestamp"], + ["1\n00:00:01,000 --> 00:00:01,000\nx", "duration"], + ["1\n00:00:00,000 --> 00:00:05,000\nx", "bounds"], + ["1\n00:00:00,000 --> 00:00:01,000\n", "markup"], + ["1\n00:00:00,000 --> 00:00:02,000\nx\n\n2\n00:00:01,000 --> 00:00:03,000\ny", "overlap"], + ["1\n00:00:00,000 --> 00:00:01,000", "text"], + ])("rejects invalid file with typed location: %s", (text, code) => { + try { + transcriptFromSrt("a", text, 4, "x.srt"); + throw new Error("accepted"); + } catch (e) { + expect(e).toBeInstanceOf(SrtImportError); + expect(e).toMatchObject({ code }); + expect((e as SrtImportError).line).toBeGreaterThan(0); + } + }); +}); diff --git a/src/lib/ai-edition/transcription/fromSrt.ts b/src/lib/ai-edition/transcription/fromSrt.ts new file mode 100644 index 0000000000..c7e4fbe12c --- /dev/null +++ b/src/lib/ai-edition/transcription/fromSrt.ts @@ -0,0 +1,82 @@ +import type { AxcutTranscript } from "../schema"; +import { transcriptFromSegments } from "./fromStt"; + +export type SrtErrorCode = + | "empty" + | "index" + | "timestamp" + | "duration" + | "bounds" + | "markup" + | "overlap" + | "text"; +export class SrtImportError extends Error { + constructor( + public readonly code: SrtErrorCode, + public readonly cue: number, + public readonly line: number, + ) { + super(`SRT ${code} (cue ${cue}, line ${line})`); + } +} + +/** Validate the whole file before returning a transcript. All times refer to source media. */ +export function transcriptFromSrt( + assetId: string, + input: string, + durationSec: number, + fileName: string, +): AxcutTranscript { + const lines = input + .replace(/^\uFEFF/, "") + .replace(/\r\n?/g, "\n") + .split("\n"); + const segments: { startSec: number; endSec: number; text: string }[] = []; + let i = 0; + const fail = (code: SrtErrorCode, line = i + 1): never => { + throw new SrtImportError(code, segments.length + 1, line); + }; + while (i < lines.length) { + if (!lines[i].trim()) { + i++; + continue; + } + if (!/^\d+$/.test(lines[i].trim()) || Number(lines[i].trim()) < 1) fail("index"); + i++; + const match = + /^(\d{2,}):([0-5]\d):([0-5]\d),(\d{3}) --> (\d{2,}):([0-5]\d):([0-5]\d),(\d{3})$/.exec( + lines[i]?.trim() ?? "", + ); + if (!match) fail("timestamp"); + const m = match!; + const startSec = Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]) + Number(m[4]) / 1000; + const endSec = Number(m[5]) * 3600 + Number(m[6]) * 60 + Number(m[7]) + Number(m[8]) / 1000; + if (endSec <= startSec) fail("duration"); + if (!Number.isFinite(durationSec) || durationSec <= 0 || endSec > durationSec) fail("bounds"); + if (segments.length && startSec < segments[segments.length - 1].endSec) fail("overlap"); + i++; + const textLine = i + 1; + const textLines: string[] = []; + while (i < lines.length && lines[i].trim()) textLines.push(lines[i++]); + const text = textLines + .join("\n") + .replace(/<\/?(?:b|i|u)>/gi, "") + .trim(); + if (!text) fail("text", textLine); + if (/<[^>]*>|\{\\[^}]*\}/.test(text)) fail("markup", textLine); + segments.push({ startSec, endSec, text }); + } + if (!segments.length) fail("empty", 1); + const result = transcriptFromSegments(assetId, segments, "auto"); + const prefix = `srt_${crypto.randomUUID()}_`; + return { + ...result, + importSource: { format: "srt", fileName, wordTiming: "estimated" }, + segments: result.segments.map((s) => ({ + ...s, + id: prefix + s.id, + wordIds: s.wordIds.map((id) => prefix + id), + })), + words: result.words.map((w) => ({ ...w, id: prefix + w.id, segmentId: prefix + w.segmentId })), + }; +} diff --git a/src/lib/ai-edition/transcription/srtCaptions.test.ts b/src/lib/ai-edition/transcription/srtCaptions.test.ts new file mode 100644 index 0000000000..132abfc800 --- /dev/null +++ b/src/lib/ai-edition/transcription/srtCaptions.test.ts @@ -0,0 +1,77 @@ +import { expect, it } from "vitest"; +import { captionLinesForAsset, deriveCaptionCues } from "../captions/cues"; +import { DEFAULT_CAPTION_SETTINGS } from "../captions/settings"; +import { captionTranslationUnits } from "../captions/translations"; +import { documentSchema } from "../schema"; +import { transcriptFromSrt } from "./fromSrt"; + +it("keeps adjacent repeated SRT cues separate in captions and translation", () => { + const transcript = transcriptFromSrt( + "a", + "1\n00:00:00,000 --> 00:00:01,000\nAgain\n\n2\n00:00:01,010 --> 00:00:02,000\nAgain", + 3, + "a.srt", + ); + expect(captionLinesForAsset(transcript, DEFAULT_CAPTION_SETTINGS, {}).map((s) => s.text)).toEqual( + ["Again", "Again"], + ); + expect(captionTranslationUnits(transcript)).toHaveLength(2); +}); +it("does not extend an imported cue past its authored end even for very short cues", () => { + const transcript = transcriptFromSrt("a", "1\n00:00:01,000 --> 00:00:01,001\nHi", 2, "a.srt"); + const lines = captionLinesForAsset(transcript, DEFAULT_CAPTION_SETTINGS, {}); + expect(lines[0].startSec).toBe(1); + expect(lines[0].endSec).toBe(1.001); +}); +it("projects only the imported asset through source-trimmed and repeated clips", () => { + const transcript = transcriptFromSrt("a", "1\n00:00:01,000 --> 00:00:03,000\nHello", 4, "a.srt"); + const document = documentSchema.parse({ + schemaVersion: 9, + project: { + id: "p", + title: "P", + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }, + transcripts: [transcript], + timeline: { + clips: [ + { + id: "c1", + assetId: "a", + origin: "user", + sourceStartSec: 2, + sourceEndSec: 4, + timelineStartSec: 0, + timelineEndSec: 2, + }, + { + id: "c2", + assetId: "a", + origin: "user", + sourceStartSec: 0, + sourceEndSec: 4, + timelineStartSec: 2, + timelineEndSec: 6, + }, + { + id: "other", + assetId: "b", + origin: "user", + sourceStartSec: 0, + sourceEndSec: 4, + timelineStartSec: 6, + timelineEndSec: 10, + }, + ], + }, + }); + expect( + deriveCaptionCues(document, { ...DEFAULT_CAPTION_SETTINGS, enabled: true }, {}).map( + ({ startMs, endMs, text }) => ({ startMs, endMs, text }), + ), + ).toEqual([ + { startMs: 0, endMs: 1000, text: "Hello" }, + { startMs: 3000, endMs: 5000, text: "Hello" }, + ]); +}); From 912f9fab7ef5aec2ffc30b2cad111552b90e40e7 Mon Sep 17 00:00:00 2001 From: auberginewly <3127221787@qq.com> Date: Wed, 28 Oct 2026 18:19:52 +0800 Subject: [PATCH 2/5] fix(transcript): preserve imports across concurrent transcription saves --- .../ai-edition/ImportSrtDialog.test.tsx | 73 +++++++++++++++++++ src/components/ai-edition/ImportSrtDialog.tsx | 26 ++++--- src/components/ai-edition/RightPanes.tsx | 7 +- .../ai-edition/TranscriptPane.gating.test.tsx | 25 ++++++- src/lib/ai-edition/captions/cues.ts | 10 ++- src/lib/ai-edition/store/transcriptImport.ts | 10 +++ .../store/transcriptionStore.test.ts | 43 +++++++++++ .../ai-edition/store/transcriptionStore.ts | 14 +++- .../transcription/srtCaptions.test.ts | 10 +++ src/native/sceneDescription.test.ts | 37 ++++++++++ 10 files changed, 240 insertions(+), 15 deletions(-) diff --git a/src/components/ai-edition/ImportSrtDialog.test.tsx b/src/components/ai-edition/ImportSrtDialog.test.tsx index 556fcb9755..6737cd94bd 100644 --- a/src/components/ai-edition/ImportSrtDialog.test.tsx +++ b/src/components/ai-edition/ImportSrtDialog.test.tsx @@ -3,7 +3,9 @@ import "@testing-library/jest-dom"; import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { I18nProvider } from "@/contexts/I18nContext"; +import { withTranscript } from "@/lib/ai-edition/document/transcript"; import { documentSchema } from "@/lib/ai-edition/schema"; +import * as projectWrites from "@/lib/ai-edition/store/projectStore"; import { useProjectStore } from "@/lib/ai-edition/store/projectStore"; import { useTranscriptionStore } from "@/lib/ai-edition/store/transcriptionStore"; import { redo, undo } from "@/lib/ai-edition/store/undo"; @@ -199,3 +201,74 @@ it("imports the primary transcript only after explicit replacement confirmation" expect(saved.assets).toEqual(d.assets); expect(saved.audioTracks).toEqual(d.audioTracks); }); + +it("waits for an existing B save then merges A into the latest saved document", async () => { + let finish!: () => void; + mocks.save.mockImplementationOnce(async (document) => { + await new Promise((resolve) => { + finish = resolve; + }); + return { success: true, document }; + }); + const old = useProjectStore.getState().document!; + const b = useProjectStore + .getState() + .saveDocument(withTranscript(old, transcriptFromSrt("b", text, 4, "b.srt")), { + history: false, + }); + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + await new Promise((resolve) => setTimeout(resolve, 0)); + const count = mocks.save.mock.calls.length; + finish(); + await b; + await waitFor(() => expect(useProjectStore.getState().document?.transcripts).toHaveLength(2)); + expect(count).toBe(1); + expect( + mocks.save.mock.calls + .at(-1)?.[0] + .transcripts.map((t: { assetId: string }) => t.assetId) + .sort(), + ).toEqual(["a", "b"]); +}); + +it("abandons import when existing document saves time out", async () => { + const wait = vi.spyOn(projectWrites, "waitForDocumentSaves").mockResolvedValueOnce("timeout"); + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + await waitFor(() => expect(wait).toHaveBeenCalled()); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(mocks.save).not.toHaveBeenCalled(); + wait.mockRestore(); +}); +it.each([ + "close", + "unmount", +])("cancels before dispatching import on %s while another save is pending", async (mode) => { + let finish!: () => void; + mocks.save.mockImplementationOnce(async (document) => { + await new Promise((resolve) => { + finish = resolve; + }); + return { success: true, document }; + }); + const b = useProjectStore + .getState() + .saveDocument(useProjectStore.getState().document!, { history: false }); + const view = show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + await new Promise((resolve) => setTimeout(resolve, 0)); + if (mode === "unmount") view.unmount(); + else fireEvent.click(screen.getByRole("button", { name: "Close" })); + finish(); + await b; + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(mocks.save).toHaveBeenCalledTimes(1); + expect(useProjectStore.getState().document?.transcripts).toHaveLength(0); +}); diff --git a/src/components/ai-edition/ImportSrtDialog.tsx b/src/components/ai-edition/ImportSrtDialog.tsx index 8e6b1548fb..cb669292bb 100644 --- a/src/components/ai-edition/ImportSrtDialog.tsx +++ b/src/components/ai-edition/ImportSrtDialog.tsx @@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from "react"; import { useScopedT } from "@/contexts/I18nContext"; import { withTranscript } from "@/lib/ai-edition/document/transcript"; import type { AxcutAsset, AxcutTranscript } from "@/lib/ai-edition/schema"; -import { useProjectStore } from "@/lib/ai-edition/store/projectStore"; +import { useProjectStore, waitForDocumentSaves } from "@/lib/ai-edition/store/projectStore"; import { runTranscriptImport } from "@/lib/ai-edition/store/transcriptImport"; import { useTranscriptionStore } from "@/lib/ai-edition/store/transcriptionStore"; import { SrtImportError, transcriptFromSrt } from "@/lib/ai-edition/transcription/fromSrt"; @@ -53,27 +53,35 @@ export function ImportSrtDialog({ onClose }: { onClose: () => void }) { return ( current?.project.id === p.projectId && current.project.id === initialProject.current && - current.assets.find((a) => a.id === p.asset.id) === p.asset && + JSON.stringify(current.assets.find((a) => a.id === p.asset.id)) === JSON.stringify(p.asset) && findAssetTranscript(current, p.asset.id) === p.previous && !busy(p.asset.id) ); }; const commit = async (p: PendingImport) => { + const token = generation.current; if (!valid(p)) { setPending(null); setError(ts("transcript.srt.stale")); return; } - const current = useProjectStore.getState().document!; setWorking(true); try { - const saved = await runTranscriptImport(p.projectId, p.asset.id, () => - useProjectStore + const saved = await runTranscriptImport(p.projectId, p.asset.id, async () => { + if ((await waitForDocumentSaves()) !== "idle") return false; + if (token !== generation.current) return "cancelled" as const; + if (!valid(p)) { + setPending(null); + setError(ts("transcript.srt.stale")); + return "stale" as const; + } + const current = useProjectStore.getState().document!; + return useProjectStore .getState() - .saveDocument(withTranscript(current, p.transcript), { history: true }), - ); - if (saved) close(); - else setError(ts("transcript.srt.saveFailed")); + .saveDocument(withTranscript(current, p.transcript), { history: true }); + }); + if (saved === true) close(); + else if (saved === false) setError(ts("transcript.srt.saveFailed")); } catch { setError(ts("transcript.srt.saveFailed")); } finally { diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx index 6c0fee6c70..12ee6d5788 100644 --- a/src/components/ai-edition/RightPanes.tsx +++ b/src/components/ai-edition/RightPanes.tsx @@ -960,7 +960,6 @@ export function TranscriptPane({ > {ts("transcript.srt.title")} - setCaptionsOpen(true)} /> {srtOpen ? setSrtOpen(false)} /> : null} ); @@ -985,8 +984,9 @@ export function TranscriptPane({ title={ts("transcript.title")} icon={} helpText={helpText} - actions={srtActions} + actions={ setCaptionsOpen(true)} />} > + {srtActions} {laneSwitch} {transcripts.some((t) => t.importSource?.format === "srt") ? (

{ts("transcript.srt.estimated")}

@@ -1039,8 +1039,9 @@ export function TranscriptPane({ title={ts("transcript.title")} icon={} helpText={helpText} - actions={srtActions} + actions={ setCaptionsOpen(true)} />} > + {srtActions} {laneSwitch} {transcripts.some((t) => t.importSource?.format === "srt") ? (

{ts("transcript.srt.estimated")}

diff --git a/src/components/ai-edition/TranscriptPane.gating.test.tsx b/src/components/ai-edition/TranscriptPane.gating.test.tsx index 787549f2e6..940027c39f 100644 --- a/src/components/ai-edition/TranscriptPane.gating.test.tsx +++ b/src/components/ai-edition/TranscriptPane.gating.test.tsx @@ -6,10 +6,12 @@ // there is nothing to press". import "@testing-library/jest-dom"; -import { cleanup, render, screen } from "@testing-library/react"; +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; import { I18nProvider } from "@/contexts/I18nContext"; import type { AxcutAsset, AxcutClip } from "@/lib/ai-edition/schema"; +import { documentSchema } from "@/lib/ai-edition/schema"; +import { useProjectStore } from "@/lib/ai-edition/store/projectStore"; import type { TranscriptGateReason } from "@/lib/ai-edition/transcription/status"; import { TranscriptPane } from "./RightPanes"; @@ -98,3 +100,24 @@ describe("transcript pane gating", () => { expect(screen.getByText("whisper-server exited")).toBeInTheDocument(); }); }); + +it("offers exactly one import button and dialog in the empty pane", () => { + const doc = documentSchema.parse({ + schemaVersion: 9, + project: { + id: "p", + title: "P", + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }, + assets: [ASSET], + timeline: { clips: CLIPS }, + }); + useProjectStore.setState({ projectId: "p", document: doc }); + renderPane(); + expect(screen.getAllByRole("button", { name: "Import SRT" })).toHaveLength(1); + fireEvent.click(screen.getByRole("button", { name: "Import SRT" })); + expect(screen.getAllByRole("dialog")).toHaveLength(1); + cleanup(); + useProjectStore.setState({ projectId: null, document: null }); +}); diff --git a/src/lib/ai-edition/captions/cues.ts b/src/lib/ai-edition/captions/cues.ts index d53e2a293e..31f374494e 100644 --- a/src/lib/ai-edition/captions/cues.ts +++ b/src/lib/ai-edition/captions/cues.ts @@ -112,7 +112,15 @@ export function captionLinesForAsset( segments: [segment], words: transcript.words.filter((word) => segment.wordIds.includes(word.id)), }; - return captionLinesForAsset(isolated, settings, translations) + const stream = + settings.language === null + ? originalWordStream(isolated) + : translatedWordStream(isolated, translations, settings.language); + return groupTimedCaptionWordsIntoLines( + stream, + settings.minWordsPerLine, + settings.maxWordsPerLine, + ) .map((line) => ({ ...line, startSec: Math.max(segment.startSec, line.startSec), diff --git a/src/lib/ai-edition/store/transcriptImport.ts b/src/lib/ai-edition/store/transcriptImport.ts index f8358931b7..31827f69ac 100644 --- a/src/lib/ai-edition/store/transcriptImport.ts +++ b/src/lib/ai-edition/store/transcriptImport.ts @@ -7,6 +7,14 @@ export function transcriptImportPending(projectId: string, assetId: string): boo export async function waitForTranscriptImport(projectId: string, assetId: string): Promise { await pending.get(projectId)?.get(assetId); } +export function projectTranscriptImportPending(projectId: string): boolean { + return (pending.get(projectId)?.size ?? 0) > 0; +} + +/** Wait before reading a whole-document snapshot, including imports on other assets. */ +export async function waitForProjectTranscriptImports(projectId: string): Promise { + while (pending.get(projectId)?.size) await Promise.all(pending.get(projectId)?.values() ?? []); +} export async function runTranscriptImport( projectId: string, assetId: string, @@ -22,8 +30,10 @@ export async function runTranscriptImport( pending.set(projectId, assets); } if (assets.has(assetId)) throw new Error("Transcript import already saving"); + const predecessors = [...assets.values()]; assets.set(assetId, done); try { + if (predecessors.length) await Promise.all(predecessors); return await save(); } finally { assets.delete(assetId); diff --git a/src/lib/ai-edition/store/transcriptionStore.test.ts b/src/lib/ai-edition/store/transcriptionStore.test.ts index eeca60a6e4..2578f8ce07 100644 --- a/src/lib/ai-edition/store/transcriptionStore.test.ts +++ b/src/lib/ai-edition/store/transcriptionStore.test.ts @@ -1,9 +1,11 @@ // @vitest-environment jsdom import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { toastText } from "@/i18n/toastText"; +import { withTranscript } from "../document/transcript"; import type { AxcutDocument, AxcutTranscript } from "../schema"; import { answerMcpHostRequest } from "./mcpDocumentHost"; import { useProjectStore } from "./projectStore"; +import { runTranscriptImport } from "./transcriptImport"; import { useTranscriptionStore, whenTranscriptionIdle } from "./transcriptionStore"; const bridgeMocks = vi.hoisted(() => ({ @@ -529,4 +531,45 @@ describe("useTranscriptionStore", () => { expect(useProjectStore.getState().document?.transcripts).toHaveLength(1); }); + it("retains imported A when unrelated B finishes during A's deferred save", async () => { + loadDocument(makeDoc(["a", "b"])); + delete (window as unknown as { electronAPI?: unknown }).electronAPI; + const engine = deferred(); + const disk = deferred(); + transcribeMocks.transcribeAsset.mockImplementation(async () => { + await engine.promise; + return transcriptFor("b"); + }); + const b = useTranscriptionStore.getState().request("b"); + bridgeMocks.save.mockImplementationOnce(async (document: AxcutDocument) => { + await disk.promise; + return { success: true, document }; + }); + const imported = runTranscriptImport("proj_1", "a", () => + useProjectStore + .getState() + .saveDocument(withTranscript(useProjectStore.getState().document!, transcriptFor("a")), { + history: true, + }), + ); + engine.release(); + await new Promise((resolve) => setTimeout(resolve, 0)); + const writesBeforeImportSettled = bridgeMocks.save.mock.calls.length; + disk.release(); + await imported; + await b; + expect(writesBeforeImportSettled).toBe(1); + expect( + useProjectStore + .getState() + .document?.transcripts.map((t) => t.assetId) + .sort(), + ).toEqual(["a", "b"]); + expect( + bridgeMocks.save.mock.calls + .at(-1)?.[0] + .transcripts.map((t: AxcutTranscript) => t.assetId) + .sort(), + ).toEqual(["a", "b"]); + }); }); diff --git a/src/lib/ai-edition/store/transcriptionStore.ts b/src/lib/ai-edition/store/transcriptionStore.ts index 558f42d5a7..ee482427f5 100644 --- a/src/lib/ai-edition/store/transcriptionStore.ts +++ b/src/lib/ai-edition/store/transcriptionStore.ts @@ -47,7 +47,12 @@ import { withTranscriptionFailure, } from "../transcription/status"; import { useProjectStore } from "./projectStore"; -import { transcriptImportPending, waitForTranscriptImport } from "./transcriptImport"; +import { + projectTranscriptImportPending, + transcriptImportPending, + waitForProjectTranscriptImports, + waitForTranscriptImport, +} from "./transcriptImport"; export interface TranscriptionJob { status: "queued" | "running" | "failed"; @@ -345,6 +350,9 @@ async function persistPermanentFailure( failure: TranscriptionFailure, ): Promise { if (!isPermanentFailure(failure.kind)) return; + // A new import can reserve between waits; recheck synchronously before reading the document. + while (projectTranscriptImportPending(projectId)) + await waitForProjectTranscriptImports(projectId); const project = useProjectStore.getState(); const doc = project.document; if (!doc || doc.project.id !== projectId) return; @@ -418,6 +426,10 @@ async function runJob(assetId: string, job: TranscriptionJob): Promise { } // The user may have switched projects while whisper was working — writing // the transcript now would attach it to the document that is loaded today. + // A new import can reserve between waits; recheck synchronously before reading the document. + while (projectTranscriptImportPending(projectId)) + await waitForProjectTranscriptImports(projectId); + if (!isCurrentRun(assetId, runId) || controller.signal.aborted) return; const current = useProjectStore.getState().document; if (!current || current.project.id !== projectId) { dropJob(assetId, runId); diff --git a/src/lib/ai-edition/transcription/srtCaptions.test.ts b/src/lib/ai-edition/transcription/srtCaptions.test.ts index 132abfc800..b0445d0c35 100644 --- a/src/lib/ai-edition/transcription/srtCaptions.test.ts +++ b/src/lib/ai-edition/transcription/srtCaptions.test.ts @@ -75,3 +75,13 @@ it("projects only the imported asset through source-trimmed and repeated clips", { startMs: 3000, endMs: 5000, text: "Hello" }, ]); }); +it("preserves intentional repeated words split into separate imported caption lines", () => { + const t = transcriptFromSrt("a", "1\n00:00:00,000 --> 00:00:02,000\nAgain Again", 3, "a.srt"); + expect( + captionLinesForAsset( + t, + { ...DEFAULT_CAPTION_SETTINGS, minWordsPerLine: 1, maxWordsPerLine: 1 }, + {}, + ).map((s) => s.text), + ).toEqual(["Again", "Again"]); +}); diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts index 010ba77084..94f5b3247f 100644 --- a/src/native/sceneDescription.test.ts +++ b/src/native/sceneDescription.test.ts @@ -20,6 +20,7 @@ import type { AxcutZoomRegion, } from "@/lib/ai-edition/schema"; import { axcutSchemaVersion } from "@/lib/ai-edition/schema"; +import { transcriptFromSrt } from "@/lib/ai-edition/transcription/fromSrt"; import { CURSOR_KIND_IDS, DEFAULT_CURSOR_THEME_ID } from "@/lib/cursor/cursorThemes"; import { DEVICE_FRAMES } from "@/lib/projectDefaults"; import { getFocusBoundsForScale } from "@/lib/zoomMath/focusUtils"; @@ -2429,6 +2430,42 @@ describe("buildSceneDescription.captions", () => { } as AxcutDocument; } + it("projects imported SRT through a timeline trim and actual speed regions for preview and export", () => { + const doc = docWithCaptions(true); + doc.transcripts = [ + transcriptFromSrt("a1", "1\n00:00:01,000 --> 00:00:05,000\nImported", 30, "captions.srt"), + ]; + doc.timeline.trimRanges = [ + { id: "cut", assetId: "a1", startSec: 2, endSec: 4, origin: "user", reason: "" }, + ]; + // speedRanges carries the document range; the speed multiplier lives in the legacy envelope. + doc.timeline.speedRanges = [{ startSec: 4, endSec: 8, reason: "" }]; + doc.legacyEditor = { + ...(doc.legacyEditor as Record), + speedRegions: [{ id: "fast", startMs: 4000, endMs: 8000, speed: 2 }], + }; + const scene = buildSceneDescription(doc); + expect( + scene.annotations.map(({ startSec, endSec, clipIndex, text }) => ({ + startSec, + endSec, + clipIndex, + text: text?.content, + })), + ).toEqual([ + { startSec: 1, endSec: 2, clipIndex: 0, text: "Imported" }, + { startSec: 4, endSec: 5, clipIndex: 1, text: "Imported" }, + ]); + expect(scene.speedRegions).toEqual([{ startSec: 4, endSec: 8, speed: 2, clipIndex: 1 }]); + // Both consumers receive source times on the same surviving clip; 4..5 plays at 2x. + expect( + scene.clips.map(({ sourceStartSec, sourceEndSec }) => ({ sourceStartSec, sourceEndSec })), + ).toEqual([ + { sourceStartSec: 0, sourceEndSec: 2 }, + { sourceStartSec: 4, sourceEndSec: 30 }, + ]); + }); + it("sends captions to the compositor as text annotations", () => { // Without this the caption would show in the DOM overlay and be missing from the // composited pixels — the preview/render gap the annotation bridge exists to close. From de112cdbb6b6a3861687e49d194b6e162afdcd6d Mon Sep 17 00:00:00 2001 From: auberginewly <3127221787@qq.com> Date: Wed, 28 Oct 2026 18:25:16 +0800 Subject: [PATCH 3/5] test(transcript): record SRT import validation and limits --- .../plans/2026-10-28-srt-import.md | 42 +++++++++++++++++++ .../testing/manual-e2e-checklist.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-28-srt-import.md diff --git a/docs/superpowers/plans/2026-10-28-srt-import.md b/docs/superpowers/plans/2026-10-28-srt-import.md new file mode 100644 index 0000000000..c24fe0a24a --- /dev/null +++ b/docs/superpowers/plans/2026-10-28-srt-import.md @@ -0,0 +1,42 @@ +# SRT Import Implementation Plan + +> **For agentic workers:** Use subagent-driven-development to implement this plan task by task, with spec and quality reviews. + +**Goal:** Import external SRT into one asset's transcript without changing media edits. + +**Architecture:** A pure parser validates every cue and builds the existing transcript shape. A focused dialog in the Transcript pane selects an asset and file, confirms replacement and commits through the existing document save/history path. Add optional SRT provenance to retain the approximate-word-timing disclosure after reload. + +**Tech Stack:** TypeScript, React, Zustand, Zod, Vitest, existing i18n. + +## Task 1: Parse source-time SRT + +Files: create `src/lib/ai-edition/transcription/fromSrt.ts` and adjacent `fromSrt.test.ts`; extend `src/lib/ai-edition/schema/index.ts` only for additive import provenance. + +- [ ] Write failing parser cases first: BOM/CRLF, multiline text, Unicode, numbered cues, hour/minute/second validation, zero/reversed duration, malformed index or arrow, empty file/cue, unsupported markup, out-of-duration timestamp, overlapping or out-of-order cues. Define supported behavior explicitly in tests; do not silently drop invalid cues. +- [ ] Run `fnm exec --using 22.22.1 npx vitest --run src/lib/ai-edition/transcription/fromSrt.test.ts` and confirm failures correspond to missing behavior. +- [ ] Implement a complete-file parser with cue and line information in typed errors. Use `transcriptFromSegments` for the document's word/segment structure; prefix fresh IDs so replacing imported text cannot accidentally inherit translations keyed to old segment IDs. Preserve SRT cue boundaries. Reject unsafe markup or convert supported formatting to plain text explicitly; React renders text, never HTML. +- [ ] Mark imported transcript provenance and disclose estimated word timing. Use `withTranscript` for both the per-asset array and primary mirror. Clear only stale caption translations for the replaced asset where IDs would otherwise carry them; retain unrelated assets/edits. +- [ ] Verify parse and document operations, including JSON/schema round-trip and unchanged timeline/audio assets. + +## Task 2: Import dialog and save + +Files: create `src/components/ai-edition/ImportSrtDialog.tsx` and adjacent component tests; modify `RightPanes.tsx` and the smallest existing store/shell integration required. + +- [ ] Write failing user scenarios for selecting a specific recording/voiceover asset, cancel, replacement confirmation, invalid file preserving old transcript, busy target disabled, save failure and successful import. +- [ ] Offer Import SRT in both empty and populated Transcript pane states. Use the existing dialog primitives and a native HTML `.srt` file input; no new broad filesystem IPC is needed for a user-selected text file. +- [ ] Select an eligible asset explicitly; default only if there is exactly one. Explain source timestamps and estimated word timing. Do not prevent silent-media subtitle imports merely because automatic transcription cannot run. +- [ ] Before writing, re-read the current project/document and busy state. If the project switched, the asset vanished, or its transcript changed during file reading/confirmation, refuse stale replacement or require renewed confirmation. Save with `{ history: true }` once. Clear pending local state on close; do not overwrite edits made while the dialog was open. +- [ ] Verify undo/redo and persistence through the existing store/bridge test pattern, not just an invoked mock callback. + +## Task 3: Caption/timeline integration and translations + +Files: existing caption cue/timeline tests; `src/i18n/locales/*/settings.json`. + +- [ ] Test imported text appears on the target's clips only, including repeated clips and source trims/speed mapping. Pin imported cue boundaries so nearby SRT cues are not silently merged by the automatic caption grouping path. +- [ ] Add translated strings in all 15 locales, including replacement warning, timestamp semantics, approximate timing, validation failures and accessible field labels. +- [ ] Run targeted suites, both TypeScript configs, `npm run lint`, `npm run i18n:check` and `npm run docs:check`. Run the full unit suite once at completion. +- [ ] Inspect the running UI if supported. Record exactly what runtime verification was possible; unavailable native desktop tools are an explicit verification gap, not a pass. + +## Acceptance + +Only the selected asset's transcript is replaced, after complete validation and confirmation. Source timing, caption mapping, history and saved documents remain consistent. No engine invocation, timeline rewrite, invented measured word alignment, unrelated abstraction or dependency addition. diff --git a/technical-documentation/testing/manual-e2e-checklist.md b/technical-documentation/testing/manual-e2e-checklist.md index 6b46ffc4ea..ad43c3ec6b 100644 --- a/technical-documentation/testing/manual-e2e-checklist.md +++ b/technical-documentation/testing/manual-e2e-checklist.md @@ -1128,3 +1128,4 @@ These checks are the human slice: an agent cannot click Apple's picker (see abov | 2026-11-17 | Exact public `v2.3.0-rc.6` @ `a4641a0b7`, AppImage SHA256 `7c79f01496c1d448807f2e24477b4dfb6ce69886edb7ef0ffef591de3acac363` | Vivo Ubuntu24.04/GNOME46 Wayland | **Fail — residual cross-file ruler seek stops playback** | Final scope follows the maintainer's RC5→RC6 diff request; observed unaffected RC5 passes are reused, never-observed unrelated checks remain uncovered. Two distinct synthetic H264/AAC files: same-asset seek keeps playing; native ruler seeks in both cross-file directions stop. Passive trace has pointerup64.2ms after pointerdown on a replacement video still paused/ready0, then metadata63.5ms later with no media error or resume. This exposes a gap in the original seek fix; the earlier Mac counterproof used clips from the same file. Public package/native hashes are unchanged. Follow-up source PR1613 and frozen-branch PR1614 address queued intent and premature play; this row remains the public RC6 verdict. Other essential exact-package capture/export/audio checks remain separately recorded. Unrelated/hardware cases are excluded. Evidence: takeover/linux/seek-one-control-provenance.json, seek-passive-event-trace-normalized.json, seek-two-assets.openscreen and C227. | | 2026-11-17 | Tag `a4641a0b7` plus only PR1613 head `22b5daeee`; private final renderer V2 SHA256 `0be50bc95ce5b5b11ace96d61440c14fe73ea534876cc01a330a8f19fe17fb32`, runtime patch ID `ecc90aba7c7c43d267946492a23cba2169485d4e` | Windows11 x64 and Vivo Linux Wayland; Mac counterproof skipped | **Pass for four targeted controls on Windows and Vivo; Partial overall** | Real OS input with distinct real files/asset IDs passes playing ruler seeks in both directions, rapid cross-file drag and initially paused seek. Windows reproduces the preserved V1 drag failure (jump to programme end in269ms) successfully with V2 in263ms, then time advances; paused seek remains fixed after1s. Vivo's forward/reverse/drag clocks advance and paused seek stays fixed across two reads. All124 renderer hashes match, native sets remain complete/unchanged and public RC6 is untouched; Windows verifies149-file runtimes and24 natives before/after. Two original unit cases and the later three-seek cancellation case fail before their fixes; final104 targeted tests, both TypeScript configurations, lint and build pass. Main PR1613 is merged with green CI and independent review PASS; frozen-branch PR1614 contains only the same four source/test files. Its tracked tree equals the compiled QA source tree. **Skipped:** Mac fixed-renderer execution, because the initial external-renderer QA route stayed on an empty target with no renderer request; no seek ran, no signature/quarantine/security change or alternate route was attempted. A signed future candidate remains needed for Mac. No new capture/benchmark/hardware matrix or whole-file Pass. Evidence: takeover/windows/RC6-CROSS-ASSET-SCRUB.md, takeover/linux/seek-v2-native-counterproof.json, takeover/mac/MAC-CROSS-ASSET-SCRUB-FIX.md and renderer manifests. | | 2026-11-17 | Official signed ARM64 `v2.3.0-rc.7` @ `460ea875510d9b54f0a298047817797f4d038d79`, CI44080825057; DMG SHA256 `a39e46e405d8aa890cc477e03765920abe450a2f7f14ddddd44523e4c046f09a` | macOS27.0.1, Apple M1 | **Partial — targeted cross-file seek 4/4 Pass** | Version7/hash verified; codesign deep/strict valid, Gatekeeper Notarized Developer ID accepted. Intact read-only mounted bundle launched via normal LaunchServices open -n with isolated QA profile, no VITE/addon/ORT/DYLD override; file renderer and bundled compositor/FFmpeg paths confirmed. Real OS inputs on two distinct files/assetIds (10s A + first10s of58.4s B): playing click A→B and B→A, real scrub drag6→14 across10s boundary, initially paused cross-file seek remains paused. Correct file src, readyState4, no video error; both timeline and video clocks advance in all three playing cases, paused values remain unchanged800ms. Native A/B still images inspected with rendered mire/source clocks. No recording/export/camera/install/security or general-checklist work. QA quit normally, original installed app preserved. RC7-MAC-SEEK.md and rc7-cross-asset-scrub/validation.json. Public release published 2026-11-17T12:42:05Z with16assets; tested DMG and updater ZIP match public SHA256/size, all three update feeds name2.3.0-rc.7 and Mac SHA512 matches the CI sidecar. Previously observed unaffected RC5/RC6 controls are reused; no whole-checklist claim or stable promotion. | +| 2026-10-28 | Dev v2.1.2, `codex/srt-import` @ `b7596902` | macOS host; Chromium renderer in browser mode | **Partial — automated subtitle import slice only** | Issue #1365: real browser controls selected an asset and SRT file, imported two cues, undid/redid, cancelled replacement, rejected a reversed cue with a line-specific error while preserving existing text, and retained imported text after reload. Narrow inspector overflow found during visual QA was fixed; pane body now fits its 315 px container. Persistent estimated-word-timing disclosure was visible. Review regressions cover cross-asset transcription/import save ordering, close/unmount before deferred save dispatch, authored repeated words and imported cue projection through real trim and 2× speed regions. Initial full suite: 5,117 passed, 2 skipped; latest affected checks: 216 passed; independent quality review: 205 passed. Both TypeScript configs, lint, i18n and docs passed. **Skipped:** computer-use MCP unavailable; actual Electron file picker/native persistence, physical capture/webcam/tray, compositor-rendered caption preview/export, Windows/Linux runtime and remainder of checklist. Browser-shim checks are not native desktop verification or release-promotion QA. | From c404712946fe0c5e77adbdf990a711c644b1a4ce Mon Sep 17 00:00:00 2001 From: auberginewly <3127221787@qq.com> Date: Wed, 18 Nov 2026 00:46:33 +0800 Subject: [PATCH 4/5] fix(transcript): finish approved SRT import workflow --- .../plans/2026-10-28-srt-import.md | 42 ---- .../ai-edition/ImportSrtDialog.test.tsx | 79 ++++++- src/components/ai-edition/ImportSrtDialog.tsx | 47 +++- src/i18n/locales/ar/settings.json | 2 +- src/i18n/locales/cs/settings.json | 2 +- src/i18n/locales/de/settings.json | 2 +- src/i18n/locales/en/settings.json | 2 +- src/i18n/locales/es/settings.json | 2 +- src/i18n/locales/fr/settings.json | 2 +- src/i18n/locales/it/settings.json | 2 +- src/i18n/locales/ja-JP/settings.json | 2 +- src/i18n/locales/ko-KR/settings.json | 2 +- src/i18n/locales/nl/settings.json | 28 ++- src/i18n/locales/pl/settings.json | 28 ++- src/i18n/locales/pt-BR/settings.json | 2 +- src/i18n/locales/ru/settings.json | 2 +- src/i18n/locales/tr/settings.json | 2 +- src/i18n/locales/vi/settings.json | 2 +- src/i18n/locales/zh-CN/settings.json | 2 +- src/i18n/locales/zh-TW/settings.json | 2 +- .../store/documentWriteAudit.test.ts | 2 +- src/lib/ai-edition/store/projectStore.ts | 6 +- .../ai-edition/store/transcriptImport.test.ts | 34 ++- src/lib/ai-edition/store/transcriptImport.ts | 26 +- .../store/transcriptionStore.test.ts | 68 +++++- .../ai-edition/store/transcriptionStore.ts | 15 +- src/lib/ai-edition/store/useTimeline.test.ts | 222 +++++++++++++++++- src/lib/ai-edition/store/useTimeline.ts | 50 +++- .../testing/manual-e2e-checklist.md | 1 + 29 files changed, 580 insertions(+), 98 deletions(-) delete mode 100644 docs/superpowers/plans/2026-10-28-srt-import.md diff --git a/docs/superpowers/plans/2026-10-28-srt-import.md b/docs/superpowers/plans/2026-10-28-srt-import.md deleted file mode 100644 index c24fe0a24a..0000000000 --- a/docs/superpowers/plans/2026-10-28-srt-import.md +++ /dev/null @@ -1,42 +0,0 @@ -# SRT Import Implementation Plan - -> **For agentic workers:** Use subagent-driven-development to implement this plan task by task, with spec and quality reviews. - -**Goal:** Import external SRT into one asset's transcript without changing media edits. - -**Architecture:** A pure parser validates every cue and builds the existing transcript shape. A focused dialog in the Transcript pane selects an asset and file, confirms replacement and commits through the existing document save/history path. Add optional SRT provenance to retain the approximate-word-timing disclosure after reload. - -**Tech Stack:** TypeScript, React, Zustand, Zod, Vitest, existing i18n. - -## Task 1: Parse source-time SRT - -Files: create `src/lib/ai-edition/transcription/fromSrt.ts` and adjacent `fromSrt.test.ts`; extend `src/lib/ai-edition/schema/index.ts` only for additive import provenance. - -- [ ] Write failing parser cases first: BOM/CRLF, multiline text, Unicode, numbered cues, hour/minute/second validation, zero/reversed duration, malformed index or arrow, empty file/cue, unsupported markup, out-of-duration timestamp, overlapping or out-of-order cues. Define supported behavior explicitly in tests; do not silently drop invalid cues. -- [ ] Run `fnm exec --using 22.22.1 npx vitest --run src/lib/ai-edition/transcription/fromSrt.test.ts` and confirm failures correspond to missing behavior. -- [ ] Implement a complete-file parser with cue and line information in typed errors. Use `transcriptFromSegments` for the document's word/segment structure; prefix fresh IDs so replacing imported text cannot accidentally inherit translations keyed to old segment IDs. Preserve SRT cue boundaries. Reject unsafe markup or convert supported formatting to plain text explicitly; React renders text, never HTML. -- [ ] Mark imported transcript provenance and disclose estimated word timing. Use `withTranscript` for both the per-asset array and primary mirror. Clear only stale caption translations for the replaced asset where IDs would otherwise carry them; retain unrelated assets/edits. -- [ ] Verify parse and document operations, including JSON/schema round-trip and unchanged timeline/audio assets. - -## Task 2: Import dialog and save - -Files: create `src/components/ai-edition/ImportSrtDialog.tsx` and adjacent component tests; modify `RightPanes.tsx` and the smallest existing store/shell integration required. - -- [ ] Write failing user scenarios for selecting a specific recording/voiceover asset, cancel, replacement confirmation, invalid file preserving old transcript, busy target disabled, save failure and successful import. -- [ ] Offer Import SRT in both empty and populated Transcript pane states. Use the existing dialog primitives and a native HTML `.srt` file input; no new broad filesystem IPC is needed for a user-selected text file. -- [ ] Select an eligible asset explicitly; default only if there is exactly one. Explain source timestamps and estimated word timing. Do not prevent silent-media subtitle imports merely because automatic transcription cannot run. -- [ ] Before writing, re-read the current project/document and busy state. If the project switched, the asset vanished, or its transcript changed during file reading/confirmation, refuse stale replacement or require renewed confirmation. Save with `{ history: true }` once. Clear pending local state on close; do not overwrite edits made while the dialog was open. -- [ ] Verify undo/redo and persistence through the existing store/bridge test pattern, not just an invoked mock callback. - -## Task 3: Caption/timeline integration and translations - -Files: existing caption cue/timeline tests; `src/i18n/locales/*/settings.json`. - -- [ ] Test imported text appears on the target's clips only, including repeated clips and source trims/speed mapping. Pin imported cue boundaries so nearby SRT cues are not silently merged by the automatic caption grouping path. -- [ ] Add translated strings in all 15 locales, including replacement warning, timestamp semantics, approximate timing, validation failures and accessible field labels. -- [ ] Run targeted suites, both TypeScript configs, `npm run lint`, `npm run i18n:check` and `npm run docs:check`. Run the full unit suite once at completion. -- [ ] Inspect the running UI if supported. Record exactly what runtime verification was possible; unavailable native desktop tools are an explicit verification gap, not a pass. - -## Acceptance - -Only the selected asset's transcript is replaced, after complete validation and confirmation. Source timing, caption mapping, history and saved documents remain consistent. No engine invocation, timeline rewrite, invented measured word alignment, unrelated abstraction or dependency addition. diff --git a/src/components/ai-edition/ImportSrtDialog.test.tsx b/src/components/ai-edition/ImportSrtDialog.test.tsx index 6737cd94bd..d457ff4952 100644 --- a/src/components/ai-edition/ImportSrtDialog.test.tsx +++ b/src/components/ai-edition/ImportSrtDialog.test.tsx @@ -1,12 +1,13 @@ // @vitest-environment jsdom import "@testing-library/jest-dom"; -import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { I18nProvider } from "@/contexts/I18nContext"; import { withTranscript } from "@/lib/ai-edition/document/transcript"; import { documentSchema } from "@/lib/ai-edition/schema"; import * as projectWrites from "@/lib/ai-edition/store/projectStore"; import { useProjectStore } from "@/lib/ai-edition/store/projectStore"; +import { transcriptImportPending } from "@/lib/ai-edition/store/transcriptImport"; import { useTranscriptionStore } from "@/lib/ai-edition/store/transcriptionStore"; import { redo, undo } from "@/lib/ai-edition/store/undo"; import { clearHistory, past } from "@/lib/ai-edition/store/undoStack"; @@ -58,6 +59,82 @@ afterEach(() => { cleanup(); vi.clearAllMocks(); }); +it("keeps the import dialog focused on media and file selection without timestamp hints", () => { + show(); + expect(screen.getByLabelText("Target media")).toBeVisible(); + expect(screen.getByLabelText("SRT file")).toBeVisible(); + expect(screen.queryByText(/Subtitle timestamps refer/)).not.toBeInTheDocument(); + expect(screen.queryByText(/Imported subtitle word timings/)).not.toBeInTheDocument(); +}); +it("offers recordings and real voiceovers, excluding generated insertions and music", () => { + const d = doc(); + d.assets.push( + { ...d.assets[0], id: "ext:synth_1", label: "Generated insertion" }, + { ...d.assets[1], id: "music", label: "Background music" }, + ); + d.audioTracks.push({ ...d.audioTracks[0], id: "m", assetId: "music", kind: "music" }); + useProjectStore.setState({ document: d }); + show(); + expect(screen.getByRole("option", { name: "Recording" })).toBeVisible(); + expect(screen.getByRole("option", { name: "Voiceover" })).toBeVisible(); + expect(screen.queryByRole("option", { name: "Generated insertion" })).not.toBeInTheDocument(); + expect(screen.queryByRole("option", { name: "Background music" })).not.toBeInTheDocument(); +}); +it("refuses a voiceover target that becomes music before replacement is confirmed", async () => { + const d = doc(); + d.transcripts = [transcriptFromSrt("b", text, 4, "old.srt")]; + useProjectStore.setState({ document: d }); + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "b" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + const replace = await screen.findByRole("button", { name: "Replace transcript" }); + act(() => { + useProjectStore.setState({ + document: { ...d, audioTracks: d.audioTracks.map((track) => ({ ...track, kind: "music" })) }, + }); + }); + fireEvent.click(replace); + await screen.findByRole("alert"); + expect(mocks.save).not.toHaveBeenCalled(); +}); +it("recovers the dialog after a save deadline while reserving the asset until the late write settles", async () => { + let finish!: () => void; + mocks.save.mockImplementationOnce(async (document) => { + await new Promise((resolve) => { + finish = resolve; + }); + return { success: true, document }; + }); + vi.useFakeTimers(); + try { + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file(); + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: "Import" })); + }); + expect(mocks.save).toHaveBeenCalledTimes(1); + await act(async () => { + await vi.advanceTimersByTimeAsync(projectWrites.DOCUMENT_SAVES_WAIT_TIMEOUT_MS); + }); + expect(screen.getByRole("alert")).toHaveTextContent(/Saving is taking longer/); + expect(screen.getByRole("button", { name: "Cancel" })).toBeEnabled(); + expect(transcriptImportPending("p", "a")).toBe(true); + await act(async () => { + finish(); + }); + expect(transcriptImportPending("p", "a")).toBe(false); + expect(useProjectStore.getState().document?.transcripts[0].assetId).toBe("a"); + expect(past).toHaveLength(1); + } finally { + if (finish) + await act(async () => { + finish(); + }); + vi.useRealTimers(); + } +}); it("requires an explicit asset and saves only that transcript with history and provenance", async () => { show(); expect(screen.getByRole("button", { name: "Import" })).toBeDisabled(); diff --git a/src/components/ai-edition/ImportSrtDialog.tsx b/src/components/ai-edition/ImportSrtDialog.tsx index cb669292bb..6c4310872c 100644 --- a/src/components/ai-edition/ImportSrtDialog.tsx +++ b/src/components/ai-edition/ImportSrtDialog.tsx @@ -1,10 +1,16 @@ import { useEffect, useRef, useState } from "react"; +import { createPortal } from "react-dom"; import { useScopedT } from "@/contexts/I18nContext"; import { withTranscript } from "@/lib/ai-edition/document/transcript"; -import type { AxcutAsset, AxcutTranscript } from "@/lib/ai-edition/schema"; -import { useProjectStore, waitForDocumentSaves } from "@/lib/ai-edition/store/projectStore"; +import type { AxcutAsset, AxcutDocument, AxcutTranscript } from "@/lib/ai-edition/schema"; +import { + saveWithDeadline, + useProjectStore, + waitForDocumentSaves, +} from "@/lib/ai-edition/store/projectStore"; import { runTranscriptImport } from "@/lib/ai-edition/store/transcriptImport"; import { useTranscriptionStore } from "@/lib/ai-edition/store/transcriptionStore"; +import { isGeneratedAssetId } from "@/lib/ai-edition/timeline/clip-parts"; import { SrtImportError, transcriptFromSrt } from "@/lib/ai-edition/transcription/fromSrt"; import { findAssetTranscript } from "@/lib/ai-edition/transcription/status"; import { ModalShell } from "./Modals"; @@ -17,6 +23,19 @@ interface PendingImport { projectId: string; } +function importTargets(document: AxcutDocument | null): AxcutAsset[] { + if (!document) return []; + const voiceovers = new Set( + document.audioTracks + .filter((track) => track.kind === "voiceover") + .map((track) => track.assetId), + ); + return document.assets.filter( + (asset) => + !isGeneratedAssetId(asset.id) && (asset.kind === "video" || voiceovers.has(asset.id)), + ); +} + /** File input is user-granted text access; no filesystem IPC or HTML rendering. */ export function ImportSrtDialog({ onClose }: { onClose: () => void }) { const ts = useScopedT("settings"); @@ -24,10 +43,7 @@ export function ImportSrtDialog({ onClose }: { onClose: () => void }) { const document = useProjectStore((s) => s.document); const jobs = useTranscriptionStore((s) => s.jobs); const initialProject = useRef(document?.project.id); - const voiceovers = new Set( - document?.audioTracks.filter((t) => t.kind === "voiceover").map((t) => t.assetId), - ); - const assets = document?.assets.filter((a) => a.kind === "video" || voiceovers.has(a.id)) ?? []; + const assets = importTargets(document); const [assetId, setAssetId] = useState(assets.length === 1 ? assets[0].id : ""); const [file, setFile] = useState(null); const [pending, setPending] = useState(null); @@ -53,6 +69,7 @@ export function ImportSrtDialog({ onClose }: { onClose: () => void }) { return ( current?.project.id === p.projectId && current.project.id === initialProject.current && + importTargets(current).some((asset) => asset.id === p.asset.id) && JSON.stringify(current.assets.find((a) => a.id === p.asset.id)) === JSON.stringify(p.asset) && findAssetTranscript(current, p.asset.id) === p.previous && !busy(p.asset.id) @@ -67,7 +84,7 @@ export function ImportSrtDialog({ onClose }: { onClose: () => void }) { } setWorking(true); try { - const saved = await runTranscriptImport(p.projectId, p.asset.id, async () => { + const operation = runTranscriptImport(p.projectId, p.asset.id, async () => { if ((await waitForDocumentSaves()) !== "idle") return false; if (token !== generation.current) return "cancelled" as const; if (!valid(p)) { @@ -80,8 +97,13 @@ export function ImportSrtDialog({ onClose }: { onClose: () => void }) { .getState() .saveDocument(withTranscript(current, p.transcript), { history: true }); }); + // A deadline releases the dialog, not the reservation: a late disk write + // must still settle before transcription or a probe reads its document. + const saved = await saveWithDeadline(operation); + if (token !== generation.current) return; if (saved === true) close(); else if (saved === false) setError(ts("transcript.srt.saveFailed")); + else if (saved === "timeout") setError(ts("transcript.srt.savePending")); } catch { setError(ts("transcript.srt.saveFailed")); } finally { @@ -90,7 +112,7 @@ export function ImportSrtDialog({ onClose }: { onClose: () => void }) { }; const read = async () => { const current = useProjectStore.getState().document; - const asset = current?.assets.find((a) => a.id === assetId); + const asset = importTargets(current).find((a) => a.id === assetId); if ( !file || !asset || @@ -137,7 +159,9 @@ export function ImportSrtDialog({ onClose }: { onClose: () => void }) { setWorking(false); } }; - return ( + // The floating inspector is transformed and clips its children. Mount the + // modal at the viewport so its backdrop and controls are not cut off by the pane. + return createPortal( void }) { } > -

{ts("transcript.srt.sourceTime")}

-

{ts("transcript.srt.estimated")}