Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.
TypeScript agent-skillscodex-clideskop-appdubbingimage-generationlocalizationskillsttsvideo-editingvideo-generationvideo-transcriptionvideo-translation
feat: add subtitle downloads and standalone SRT translation
Joshua Yin Junxi56ed065fff40
diff --git a/apps/daemon/src/creator/command-dispatcher.ts b/apps/daemon/src/creator/command-dispatcher.tsindex 63f2078e..57cdb967 100644--- a/apps/daemon/src/creator/command-dispatcher.ts+++ b/apps/daemon/src/creator/command-dispatcher.ts@@ -376,10 +376,10 @@ function stageRequestProgress(const selectedOption = options.find(candidate => (isJsonRecord(candidate)&& candidate.id === optionId- && (candidate.mediaType === 'video' || candidate.mediaType === 'audio')+ && (candidate.mediaType === 'video' || candidate.mediaType === 'audio' || candidate.mediaType === 'subtitle')));const selectedMediaType = isJsonRecord(selectedOption)- && (selectedOption.mediaType === 'video' || selectedOption.mediaType === 'audio')+ && (selectedOption.mediaType === 'video' || selectedOption.mediaType === 'audio' || selectedOption.mediaType === 'subtitle')? selectedOption.mediaType: undefined;if (diff --git a/apps/daemon/src/creator/download/executor.ts b/apps/daemon/src/creator/download/executor.tsindex cf2e5c7e..30a5f8fa 100644--- a/apps/daemon/src/creator/download/executor.ts+++ b/apps/daemon/src/creator/download/executor.ts@@ -1,6 +1,6 @@import { createHash } from 'node:crypto';import { createReadStream } from 'node:fs';-import { readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';+import { mkdir, readdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';import { basename, dirname, extname, join, resolve } from 'node:path';import { StringDecoder } from 'node:string_decoder';import type {@@ -20,6 +20,7 @@ import { CreatorExecutorError } from '../executor.js';import { sanitizeIssueDetail } from '../issues.js';import { spawnCreatorProcess } from '../process-tree.js';import { validateMediaFile } from '../validators/media.js';+import { validateSrtFile } from '../validators/srt.js';import { withYtDlpProxy } from '../yt-dlp/args.js';import type { YtDlpRuntime } from '../yt-dlp/runtime.js';import { parseDownloadProbe } from './probe-parser.js';@@ -208,6 +209,10 @@ async function downloadSelectedOption();}+ if (option.mediaType === 'subtitle') {+ return downloadSubtitle(input, url, proxy, stage, probe, option);+ }+stage.reportProgress({status: 'running',phase: 'preparing_download',@@ -293,6 +298,63 @@ async function downloadSelectedOption(};}+async function downloadSubtitle(+ input: DownloadExecutorOptions,+ url: string,+ proxy: string,+ stage: CreatorExecutorInput,+ probe: DownloadProbe,+ option: DownloadOption+): Promise<CreatorExecutorResult> {+ const { subtitleLanguage, subtitleSource } = option;+ if (!subtitleLanguage || (subtitleSource !== 'manual' && subtitleSource !== 'automatic')) {+ throw new CreatorExecutorError('format_unavailable', 'The selected subtitle track is invalid');+ }+ const outputDir = join(stage.workdir, 'subtitles');+ await mkdir(outputDir, { recursive: true });+ stage.reportProgress({ status: 'running', phase: 'preparing_download', percent: null, message: 'Downloading the selected subtitles as SRT' });+ const ytDlp = currentYtDlpRuntime(input, url);+ const languagePattern = `^${subtitleLanguage.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`;+ await run(ytDlp.executable, [+ ...ytDlp.prefixArgs,+ ...YT_DLP_UTF8_ARGS,+ ...withYtDlpProxy([+ '--skip-download', '--no-playlist', '--windows-filenames',+ ...(option.playlistIndex === undefined ? [] : ['--playlist-items', String(option.playlistIndex)]),+ ...(subtitleSource === 'automatic'+ ? ['--write-auto-subs', '--no-write-subs']+ : ['--write-subs', '--no-write-auto-subs']),+ '--sub-langs', languagePattern,+ '--sub-format', 'srt/vtt/ttml', '--convert-subs', 'srt',+ '--ffmpeg-location', input.ffmpegPath,+ '-o', join(outputDir, 'OpenCreator-%(title).120B-%(id)s.%(ext)s'),+ normalizeSourceUrl(url)+ ], proxy)+ ], stage, undefined, ytDlp.env);+ const files = (await readdir(outputDir)).filter(file => file.endsWith('.srt'));+ if (files.length !== 1) {+ throw new CreatorExecutorError('download_output_missing', 'The selected subtitles are no longer available. Analyze the video again.');+ }+ const path = await safeOutputPath(stage.workdir, join(outputDir, files[0]!));+ const cues = await validateSrtFile(path, { allowOverlaps: true });+ const info = await stat(path);+ const sha256 = await sha256File(path);+ const progress = { status: 'succeeded', phase: 'completed', percent: 100, message: 'Subtitles downloaded to the project' };+ stage.reportProgress(progress);+ return {+ outputs: [{+ kind: 'source_subtitle', status: 'completed', path,+ metadata: {+ ...sourceMetadata(probe), fileName: basename(path), size: info.size, bytes: info.size,+ sha256, mimeType: 'application/x-subrip', optionId: option.id,+ mediaType: 'subtitle', container: 'srt', subtitleLanguage,+ subtitleSource, cueCount: cues.length+ }+ }],+ progress+ };+}+async function preparePreviewSource(input: DownloadExecutorOptions,stage: CreatorExecutorInputdiff --git a/apps/daemon/src/creator/download/probe-parser.ts b/apps/daemon/src/creator/download/probe-parser.tsindex 70afd0e4..b04abccb 100644--- a/apps/daemon/src/creator/download/probe-parser.ts+++ b/apps/daemon/src/creator/download/probe-parser.ts@@ -34,6 +34,16 @@ const probeSchema = z.object({width: z.number().nullish(),height: z.number().nullish(),language: z.string().nullish(),+ subtitles: z.record(z.array(z.object({+ ext: z.string().nullish(),+ url: z.string().nullish(),+ name: z.string().nullish()+ }).passthrough())).nullish(),+ automatic_captions: z.record(z.array(z.object({+ ext: z.string().nullish(),+ url: z.string().nullish(),+ name: z.string().nullish()+ }).passthrough())).nullish(),formats: z.array(formatSchema).default([])}).passthrough();@@ -116,10 +126,36 @@ function parseSingleDownloadProbe(value: unknown, requestedUrl: string): Downloawidth: parsed.width ?? largestDimension(formats, 'width'),height: parsed.height ?? largestDimension(formats, 'height'),formats,- options: createDownloadOptions(formats, parsed.duration ?? null)+ options: [+ ...createDownloadOptions(formats, parsed.duration ?? null),+ ...createSubtitleOptions(parsed.subtitles, 'manual'),+ ...createSubtitleOptions(parsed.automatic_captions, 'automatic')+ ]};}+function createSubtitleOptions(+ tracks: Record<string, Array<{ ext?: string | null; url?: string | null; name?: string | null }>> | null | undefined,+ source: 'manual' | 'automatic'+): DownloadOption[] {+ return Object.entries(tracks ?? {}).flatMap(([language, formats]) => {+ if (!language || language === 'live_chat') return [];+ const format = formats.find(candidate => (+ ['srt', 'vtt', 'ttml'].includes(candidate.ext ?? '')+ && /^https?:\/\//i.test(candidate.url ?? '')+ ));+ if (format === undefined) return [];+ return [{+ id: `subtitle-${source}-${encodeURIComponent(language)}`,+ mediaType: 'subtitle',+ container: 'srt',+ subtitleLanguage: language,+ ...(format.name ? { subtitleName: format.name } : {}),+ subtitleSource: source+ }];+ });+}+function createDownloadOptions(formats: DownloadProbeFormat[],duration: number | nulldiff --git a/apps/daemon/src/creator/krillin/adapter.ts b/apps/daemon/src/creator/krillin/adapter.tsindex 6b40936d..dd367700 100644--- a/apps/daemon/src/creator/krillin/adapter.ts+++ b/apps/daemon/src/creator/krillin/adapter.ts@@ -260,7 +260,8 @@ export function normalizeKrillinFailure(error: { code?: string; kind?: string; mexport function buildKrillinStageOptions(input: CreatorExecutorInput): Record<string, unknown> {const state = input.job.state;return compactObject({- sourceUrl: typeof state.sourceUrl === 'string' ? normalizeVideoSourceUrl(state.sourceUrl) : undefined,+ sourceType: state.sourceType,+ sourceUrl: state.sourceType !== 'subtitle' && typeof state.sourceUrl === 'string' ? normalizeVideoSourceUrl(state.sourceUrl) : undefined,originLanguage: normalizeKrillinLanguage(typeof state.sourceLanguage === 'string' ? state.sourceLanguage : undefined),diff --git a/apps/daemon/src/creator/krillin/cli-runner.ts b/apps/daemon/src/creator/krillin/cli-runner.tsindex 11547eae..764c6b9b 100644--- a/apps/daemon/src/creator/krillin/cli-runner.ts+++ b/apps/daemon/src/creator/krillin/cli-runner.ts@@ -244,16 +244,19 @@ export function buildKrillinCliCommandArguments(const sourceUrl = stringOption(options, 'sourceUrl');const mediaCache = sourceUrl ? ['--media-workdir', join(dirname(stage.workdir), 'source-media', createHash('sha256').update(sourceUrl).digest('hex').slice(0, 16))] : [];if (command === 'subtitle') {- const source = sourceOverride ?? resolveKrillinCliSource(artifacts, options);- if (!source) throw new CreatorExecutorError('creator_stage_input_missing', 'Subtitle input video or URL is required');+ const subtitleOnly = options.sourceType === 'subtitle';+ const source = subtitleOnly ? undefined : sourceOverride ?? resolveKrillinCliSource(artifacts, options);const sourceOnly = booleanOption(options, 'sourceOnly', false);- const importedTarget = artifactPath(artifacts, 'target_subtitle');+ const importedTarget = subtitleOnly ? undefined : artifactPath(artifacts, 'target_subtitle');const importedSource = artifactPath(artifacts, 'source_subtitle');const imported = importedTarget ?? importedSource;+ if (subtitleOnly ? !importedSource : !source && !imported) {+ throw new CreatorExecutorError('creator_stage_input_missing', 'A video, URL or imported source SRT is required');+ }return ['subtitle',- source,- ...(!sourceOnly && booleanOption(options, 'prepareVideo', true) ? ['--prepare-video'] : []),+ ...(source ? [source] : []),+ ...(!subtitleOnly && source && !sourceOnly && booleanOption(options, 'prepareVideo', true) ? ['--prepare-video'] : []),'--origin-lang', requiredOption(options, 'originLanguage'),'--target-lang', requiredOption(options, 'targetLanguage'),'--caption-source', stringOption(options, 'captionSource') ?? 'any',diff --git a/apps/daemon/src/creator/preflight.ts b/apps/daemon/src/creator/preflight.tsindex 3a37f5d8..2b900dd0 100644--- a/apps/daemon/src/creator/preflight.ts+++ b/apps/daemon/src/creator/preflight.ts@@ -113,6 +113,11 @@ export function createCreatorPreflight(input: {}, { label: 'Open diagnostics', deepLink: '#/settings?tab=diagnostics' });}const inputState = inputSnapshot?.state ?? job.state;+ if (inputState.sourceType === 'subtitle' && stage.id === 'subtitle'+ && !job.artifacts.some(artifact => artifact.id === inputState.importedSourceSubtitleId+ && artifact.kind === 'source_subtitle' && artifact.status === 'completed')) {+ add('blocked', { id: 'input-subtitle', title: 'Subtitle file missing', message: 'Import a source SRT file to translate.', executionMode: 'local' });+ }if (stage.resultVersionPolicy === 'attach' && inputSnapshot === undefined) {add('blocked', { id: 'input-result-version', title: 'Select a project version', message: 'Select a saved project version before preparing the preview video.', executionMode: 'local' });}@@ -252,7 +257,7 @@ export function createCreatorPreflight(input: {}}}- if (input.validateRuntimeAssets !== false && (stage.executor === 'download' || stage.executor === 'cover-analysis' || (stage.executor === 'krillinai' && job.state.sourceType !== 'file'))) {+ if (input.validateRuntimeAssets !== false && (stage.executor === 'download' || stage.executor === 'cover-analysis' || (stage.executor === 'krillinai' && job.state.sourceType !== 'file' && job.state.sourceType !== 'subtitle'))) {let runtime: YtDlpRuntime | undefined;try { runtime = input.getYtDlpRuntime?.(); } catch { runtime = undefined; }if (runtime === undefined) add('blocked', {@@ -278,7 +283,7 @@ export function createCreatorPreflight(input: {}, { label: 'Open local component settings', deepLink: '#/settings?tab=local-components' });}}- if (stage.executor === 'krillinai' && (job.state.sourceType === 'file' || job.state.preferPlatformCaptions === false) && ['whisper.cpp', 'whisperkit', 'faster-whisper'].includes(config.transcription.provider)) {+ if (stage.executor === 'krillinai' && job.state.sourceType !== 'subtitle' && (job.state.sourceType === 'file' || job.state.preferPlatformCaptions === false) && ['whisper.cpp', 'whisperkit', 'faster-whisper'].includes(config.transcription.provider)) {const provider = input.readCapabilities().transcription.providers.find(candidate => candidate.provider === config.transcription.provider);if (provider?.available !== true) add('blocked', {id: 'transcription-capability',@@ -316,11 +321,11 @@ async function checkProviderConfig(if (stage.executor === 'krillinai') {if (stage.id === 'subtitle'- && !job.artifacts.some(artifact => (+ && (job.state.sourceType === 'subtitle' || !job.artifacts.some(artifact => (artifact.id === job.state.importedTargetSubtitleId&& artifact.kind === 'target_subtitle'&& artifact.status === 'completed'- ))+ )))) needs.add('llm');if (stage.id === 'tts' && job.state.dubbing === true) needs.add('tts');}@@ -424,7 +429,7 @@ async function checkProviderConfig(else add('ready', { id: 'video-provider', title: 'Video service', message: `${provider} / ${settings.model} is configured.`, executionMode: 'remote' });}}- if (stage.executor === 'krillinai' && stage.id === 'subtitle' && (job.state.sourceType === 'file' || job.state.preferPlatformCaptions === false)) {+ if (stage.executor === 'krillinai' && stage.id === 'subtitle' && job.state.sourceType !== 'subtitle' && (job.state.sourceType === 'file' || job.state.preferPlatformCaptions === false)) {const provider = capabilities.transcription.providers.find(candidate => candidate.provider === config.transcription.provider);if (provider?.available !== true) return;if (config.transcription.provider === 'openai' && !config.transcription.openai.apiKey.trim()) {diff --git a/apps/daemon/src/creator/stage-runner.ts b/apps/daemon/src/creator/stage-runner.tsindex f4e2087c..06fad09f 100644--- a/apps/daemon/src/creator/stage-runner.ts+++ b/apps/daemon/src/creator/stage-runner.ts@@ -675,6 +675,7 @@ export function resolveCreatorStageInputs(function creatorInputArtifactEnabled(job: CreatorJob, kind: string): boolean {if (job.templateId !== 'video-translation') return true;+ if (job.state.sourceType === 'subtitle' && (kind === 'source_video' || kind === 'target_subtitle')) return false;if ((kind === 'dubbed_audio' || kind === 'dubbed_video')&& job.state.dubbing !== truediff --git a/apps/daemon/src/creator/templates/video-download.ts b/apps/daemon/src/creator/templates/video-download.tsindex d0b7e653..6414edf2 100644--- a/apps/daemon/src/creator/templates/video-download.ts+++ b/apps/daemon/src/creator/templates/video-download.ts@@ -32,7 +32,7 @@ export function createVideoDownloadTemplate(): CreatorTemplateDefinition {renderer: 'video-download',inputSchema: z.object({sourceUrl: z.string().default(''),- mediaType: z.enum(['video', 'audio']).default('video'),+ mediaType: z.enum(['video', 'audio', 'subtitle']).default('video'),selectedOptionId: z.string().nullable().default(null),currentStage: z.string().nullable().default(null)}).passthrough() as never,@@ -58,7 +58,8 @@ export function createVideoDownloadTemplate(): CreatorTemplateDefinition {}],outputArtifacts: [{ kind: 'source_video', status: 'completed' },- { kind: 'source_audio', status: 'completed' }+ { kind: 'source_audio', status: 'completed' },+ { kind: 'source_subtitle', status: 'completed' }]}],@@ -81,11 +82,12 @@ export function createVideoDownloadTemplate(): CreatorTemplateDefinition {],outputs: [{ kind: 'source_video', required: false },- { kind: 'source_audio', required: false }+ { kind: 'source_audio', required: false },+ { kind: 'source_subtitle', required: false }],agentGuidance: [- '支持公开的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest 和 Reddit 视频链接,可下载视频或提取音频。',- '先设置 sourceUrl 并运行 probe,再读取最新 download_probe.options;只选择其中与用户请求的 video 或 audio 对应的 option.id。',+ '支持公开的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest 和 Reddit 视频链接,可下载视频、提取音频或下载来源提供的 SRT 字幕。',+ '先设置 sourceUrl 并运行 probe,再读取最新 download_probe.options;只选择其中与用户请求的 video、audio 或 subtitle 对应的 option.id,字幕须匹配语言和人工或自动来源。','更新 selectedOptionId 和 mediaType 后运行 download;不得自行构造或写入 formatId。若 probe 没有对应选项,再说明该链接无法提供所需媒体。'].join(' ')};diff --git a/apps/daemon/src/creator/templates/video-translation-actions.ts b/apps/daemon/src/creator/templates/video-translation-actions.tsindex 516cf17f..58052b26 100644--- a/apps/daemon/src/creator/templates/video-translation-actions.ts+++ b/apps/daemon/src/creator/templates/video-translation-actions.ts@@ -20,10 +20,13 @@ export function createVideoTranslationWorkflow(input: {}) {async function validateStage(job: CreatorJob, stageId: string): Promise<void> {if (job.templateId !== 'video-translation') return;+ if (job.state.sourceType === 'subtitle' && stageId !== 'subtitle') {+ throw new VideoTranslationWorkflowError('creator_action_not_allowed', 'Subtitle-only tasks only support subtitle translation');+ }if (stageId === 'subtitle') {validateSource(job);await validateBilibiliSource(job, input.videoMetadataService);- if (job.artifacts.some(artifact => artifact.id === job.state.importedTargetSubtitleId && artifact.kind === 'target_subtitle' && artifact.status === 'completed')) return;+ if (job.state.sourceType !== 'subtitle' && job.artifacts.some(artifact => artifact.id === job.state.importedTargetSubtitleId && artifact.kind === 'target_subtitle' && artifact.status === 'completed')) return;const config = await input.configStore.read();if (config.llm.source === 'custom'@@ -126,7 +129,7 @@ export class VideoTranslationWorkflowError extends Error {}export async function validateBilibiliSource(job: CreatorJob, service?: VideoMetadataService): Promise<void> {- if (job.state.sourceType === 'file' || typeof job.state.sourceUrl !== 'string') return;+ if (job.state.sourceType === 'file' || job.state.sourceType === 'subtitle' || typeof job.state.sourceUrl !== 'string') return;let host: string;try {host = new URL(job.state.sourceUrl).hostname.toLowerCase();@@ -158,6 +161,13 @@ export async function validateBilibiliSource(job: CreatorJob, service?: VideoMet}function validateSource(job: CreatorJob): void {+ if (job.state.sourceType === 'subtitle') {+ if (!job.artifacts.some(artifact => artifact.id === job.state.importedSourceSubtitleId+ && artifact.kind === 'source_subtitle' && artifact.status === 'completed')) {+ throw new VideoTranslationWorkflowError('creator_source_missing', 'An imported source SRT file is required');+ }+ return;+ }if (job.state.sourceType === 'file') {if (!job.artifacts.some(artifact => artifact.kind === 'source_video' && artifact.status === 'completed')) {throw new VideoTranslationWorkflowError('creator_source_missing', 'Registered local source video is required');@@ -245,6 +255,7 @@ function queueNextStage(}function nextWorkflowStage(job: CreatorJob, completedStageId: string): string | undefined {+ if (job.state.sourceType === 'subtitle') return undefined;if (completedStageId === 'subtitle') {if (job.state.dubbing === true) return 'tts';return firstRenderStage(job);diff --git a/apps/daemon/src/creator/templates/video-translation-results.ts b/apps/daemon/src/creator/templates/video-translation-results.tsindex 299ca48e..3ef61718 100644--- a/apps/daemon/src/creator/templates/video-translation-results.ts+++ b/apps/daemon/src/creator/templates/video-translation-results.ts@@ -8,6 +8,7 @@ export function videoTranslationArtifactRefsPatch(const remove = (...kinds: string[]) => {for (const kind of kinds) patch[kind] = [];};+ if (state.sourceType === 'subtitle') remove('source_video', 'dubbed_audio', 'dubbed_video', 'horizontal_video', 'vertical_video');if (stageId === 'subtitle') {remove('dubbed_audio', 'dubbed_video', 'horizontal_video', 'vertical_video');diff --git a/apps/daemon/src/creator/templates/video-translation.ts b/apps/daemon/src/creator/templates/video-translation.tsindex e4709544..498f8444 100644--- a/apps/daemon/src/creator/templates/video-translation.ts+++ b/apps/daemon/src/creator/templates/video-translation.ts@@ -19,7 +19,7 @@ function createVideoTranslationTemplateDefinition(version: 1 | 2): CreatorTemplaversion,renderer: 'video-translation',inputSchema: z.object({- sourceType: z.enum(['url', 'file']).default('url'),+ sourceType: z.enum(['url', 'file', 'subtitle']).default('url'),sourceUrl: z.string().default(''),sourceArtifactId: z.string().nullable().optional(),importedSourceSubtitleId: z.string().nullable().optional(),@@ -48,7 +48,9 @@ function createVideoTranslationTemplateDefinition(version: 1 | 2): CreatorTemplatext: z.string()})).default([]),currentStage: z.string().nullable().default(null)- }).passthrough() as never,+ }).passthrough().transform(state => state.sourceType === 'subtitle'+ ? { ...state, composeVideo: false, dubbing: false }+ : state) as never,stages: [{id: 'subtitle',@@ -185,6 +187,7 @@ function createVideoTranslationTemplateDefinition(version: 1 | 2): CreatorTempla{ kind: 'vertical_video', required: false }],agentGuidance: [+ '仅翻译字幕文件时设置 sourceType 为 subtitle,使用 import-subtitle 导入 source_subtitle,只运行 subtitle 阶段,不需要 sourceUrl、视频、ASR、配音、合成或字幕样式。','导入用户提供的 UTF-8 SRT 使用 import-subtitle,input 包含 fileName、contentBase64(原文件字节的 base64,最多512 KiB)、kind(source_subtitle 或 target_subtitle)和 language。原文跳过 ASR,译文跳过 ASR 与翻译。不要编造字幕。','帮助用户调整视频翻译内容与参数,修改前读取最新 revision。','更新设置必须写入 input.patch。',diff --git a/apps/daemon/test/integration/creator-api.test.ts b/apps/daemon/test/integration/creator-api.test.tsindex 7901100a..0b55c387 100644--- a/apps/daemon/test/integration/creator-api.test.ts+++ b/apps/daemon/test/integration/creator-api.test.ts@@ -33,6 +33,54 @@ afterEach(async () => {});describe('creator api', () => {+ it('translates a standalone SRT without video and stops after the subtitle stage', async () => {+ const calls: string[] = [];+ await setupServer({ creatorExecutors: [{ id: 'krillinai', async run(stage) {+ calls.push(stage.stageRun.stageId);+ expect(stage.job.state.sourceType).toBe('subtitle');+ expect(stage.inputArtifacts.map(artifact => artifact.kind)).toEqual(['source_subtitle']);+ expect(readFileSync(stage.inputArtifacts[0]!.path!, 'utf8')).toContain('00:00:02,250 --> 00:00:04,750');+ const path = join(stage.workdir, 'translated.srt');+ writeFileSync(path, '1\n00:00:02,250 --> 00:00:04,750\n你好\n');+ return { outputs: [{ kind: 'target_subtitle', status: 'completed', path }] };+ } }] });+ const created = await request('POST', '/creator/jobs', { projectId: 'project_srt', templateId: 'video-translation', state: {+ sourceType: 'subtitle', sourceUrl: '', sourceLanguage: 'en', targetLanguage: 'zh_cn',+ dubbing: true, composeVideo: true, videoFormat: 'all'+ } });+ expect(created.statusCode).toBe(201);+ const job = created.json().job;+ expect(job.state).toMatchObject({ composeVideo: false, dubbing: false });+ const missing = await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'run-stage', expectedRevision: job.revision, input: { stageId: 'subtitle', workflow: true } });+ expect(missing.statusCode).toBe(400);+ const imported = await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'import-subtitle', expectedRevision: job.revision, input: {+ kind: 'source_subtitle', language: 'en', fileName: 'source.srt',+ contentBase64: Buffer.from('1\n00:00:02,250 --> 00:00:04,750\nHello\n').toString('base64')+ } });+ expect(imported.statusCode).toBe(200);+ const started = await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'run-stage', expectedRevision: imported.json().job.revision, input: { stageId: 'subtitle', workflow: true } });+ expect(started.statusCode).toBe(200);+ const completed = await waitForCreatorJob(job.id, job => job.status === 'completed');+ expect(calls).toEqual(['subtitle']);+ expect(completed.artifacts.map((artifact: { kind: string }) => artifact.kind)).toEqual(['source_subtitle', 'target_subtitle']);+ const target = completed.artifacts.find((artifact: { kind: string }) => artifact.kind === 'target_subtitle');+ const download = await request('GET', `/creator/jobs/${job.id}/artifacts/${target.id}/content`);+ expect(download.statusCode).toBe(200);+ const edited = await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'edit-subtitle', expectedRevision: completed.revision, input: {+ artifactId: target.id, baseResultVersion: completed.state.resultVersion, preserveResultVersion: true,+ cues: [{ id: 1, start: '00:00:02,250', end: '00:00:04,750', text: '你好世界', sourceText: 'Hello' }]+ } });+ expect(edited.statusCode).toBe(200);+ const editedJob = edited.json().job;+ const editedTarget = editedJob.artifacts.find((artifact: { metadata: { editedFromArtifactId?: string } }) => artifact.metadata.editedFromArtifactId === target.id);+ expect(readFileSync(editedTarget.path, 'utf8')).toContain('00:00:02,250 --> 00:00:04,750\n你好世界');+ expect(editedJob.artifacts.some((artifact: { kind: string }) => artifact.kind === 'bilingual_subtitle')).toBe(true);+ expect(calls).toEqual(['subtitle']);+ for (const stageId of ['tts', 'render-horizontal', 'render-vertical', 'prepare-source-video']) {+ const blocked = await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'run-stage', expectedRevision: editedJob.revision, input: { stageId } });+ expect(blocked.statusCode).toBe(400);+ }+ });it.each(['source_subtitle', 'target_subtitle'])('imports %s and runs downstream workflow with the persisted input', async kind => {const calls: string[] = [];await setupServer({ llmConfigured: kind === 'source_subtitle', creatorExecutors: [{diff --git a/apps/daemon/test/integration/creator-video-download.test.ts b/apps/daemon/test/integration/creator-video-download.test.tsindex 5d957584..9fced00e 100644--- a/apps/daemon/test/integration/creator-video-download.test.ts+++ b/apps/daemon/test/integration/creator-video-download.test.ts@@ -1,4 +1,5 @@import type { CreatorExecutor } from '../../src/creator/executor.js';+import type { CreatorJson } from '@opencreator/protocol';import type { FastifyInstance } from 'fastify';import { mkdtemp, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';@@ -17,6 +18,36 @@ afterEach(async () => {});describe('creator video download', () => {+ it('queues a probed subtitle option and serves its SRT artifact', async () => {+ tempDir = await mkdtemp(join(tmpdir(), 'creator-subtitle-download-api-'));+ server = await buildServer({ token: 'secret', dataDir: tempDir, codexHome: join(tempDir, 'codex-home'), creatorExecutors: [fakeDownloadExecutor(true)] });+ const { job } = (await request('POST', '/creator/jobs', {+ projectId: 'project_download', templateId: 'video-download', creationKey: 'subtitle-flow',+ state: { sourceUrl: 'https://www.youtube.com/watch?v=download-demo' }+ })).json();+ expect((await request('POST', `/creator/jobs/${job.id}/actions`, {+ action: 'run-stage', expectedRevision: job.revision, input: { stageId: 'probe' }+ })).statusCode).toBe(200);+ const probed = await waitForStage(job.id, 'probe');+ const rejected = await request('POST', `/creator/jobs/${job.id}/actions`, {+ action: 'run-stage', expectedRevision: probed.revision,+ input: { stageId: 'download', optionId: 'subtitle-manual-en', mediaType: 'video' }+ });+ expect(rejected.statusCode).toBe(400);+ const queued = await request('POST', `/creator/jobs/${job.id}/actions`, {+ action: 'run-stage', expectedRevision: probed.revision,+ input: { stageId: 'download', optionId: 'subtitle-manual-en', mediaType: 'subtitle' }+ });+ expect(queued.statusCode).toBe(200);+ const downloaded = await waitForStage(job.id, 'download');+ const artifact = downloaded.artifacts.find((item: { kind: string }) => item.kind === 'source_subtitle');+ expect(artifact).toMatchObject({ status: 'completed', metadata: { optionId: 'subtitle-manual-en', mediaType: 'subtitle' } });+ const content = await server.inject({ method: 'GET', url: `/creator/jobs/${job.id}/artifacts/${artifact.id}/content`, headers: { authorization: 'Bearer secret' } });+ expect(content.statusCode).toBe(200);+ expect(content.headers['content-type']).toContain('application/x-subrip');+ expect(content.body).toContain('Hello subtitles');+ });+it('runs probe and download stages, then imports the video into translation', async () => {tempDir = await mkdtemp(join(tmpdir(), 'creator-video-download-api-'));server = await buildServer({@@ -153,13 +184,13 @@ describe('creator video download', () => {});});-function fakeDownloadExecutor(): CreatorExecutor {+function fakeDownloadExecutor(subtitles = false): CreatorExecutor {return {id: 'download',async run(stage) {if (stage.stageRun.stageId === 'probe') {const path = join(stage.workdir, 'probe.json');- const metadata = {+ const metadata: Record<string, CreatorJson> = {id: 'download-demo',title: 'Download Demo',requestedUrl: 'https://www.youtube.com/watch?v=download-demo',@@ -179,7 +210,7 @@ function fakeDownloadExecutor(): CreatorExecutor {height: 1080,videoFormatId: '399',audioFormatId: '140'- }]+ }, ...(subtitles ? [{ id: 'subtitle-manual-en', mediaType: 'subtitle', container: 'srt', subtitleLanguage: 'en', subtitleSource: 'manual' }] : [])]};await writeFile(path, JSON.stringify(metadata));return {@@ -191,6 +222,13 @@ function fakeDownloadExecutor(): CreatorExecutor {}]};}+ if (stage.stageRun.progress.mediaType === 'subtitle') {+ const path = join(stage.workdir, 'Download Demo.en.srt');+ await writeFile(path, '1\n00:00:00,000 --> 00:00:01,000\nHello subtitles\n');+ return { outputs: [{ kind: 'source_subtitle', status: 'completed', path, metadata: {+ fileName: 'Download Demo.en.srt', mimeType: 'application/x-subrip', optionId: 'subtitle-manual-en', mediaType: 'subtitle', subtitleLanguage: 'en'+ } }] };+ }const path = join(stage.workdir, 'Download Demo.mp4');await writeFile(path, 'downloaded-video');return {diff --git a/apps/daemon/test/unit/creator-download-executor.test.ts b/apps/daemon/test/unit/creator-download-executor.test.tsindex 1c6f93e0..d67756c9 100644--- a/apps/daemon/test/unit/creator-download-executor.test.ts+++ b/apps/daemon/test/unit/creator-download-executor.test.ts@@ -29,6 +29,61 @@ afterEach(async () => {});describe('creator download executor', () => {+ it.each([null, 'not an SRT file'])('rejects missing or invalid subtitle output: %s', async subtitleContent => {+ const executor = createDownloadExecutor(await fakeBinaries({ subtitleContent }));+ const workdir = join(tempDir, 'subtitle-failure');+ await mkdir(workdir);+ const sourceUrl = 'https://youtu.be/demo';+ const probe = parseDownloadProbe({ id: 'demo', title: 'Subtitle video', formats: [], subtitles: {+ en: [{ ext: 'vtt', url: 'https://example.com/en.vtt' }]+ } }, sourceUrl);+ const stage = stageInput({ workdir, stageId: 'download', state: {+ sourceUrl, selectedOptionId: 'subtitle-manual-en', mediaType: 'subtitle'+ }, inputArtifacts: [await writeProbeArtifact(workdir, probe)] });+ await expect(executor.run(stage)).rejects.toThrow(subtitleContent === null ? 'no longer available' : 'invalid_srt');+ expect(stage.reportProgress).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'succeeded' }));+ });++ it('lists usable manual and automatic subtitle tracks without exposing signed URLs', () => {+ const probe = parseDownloadProbe({+ id: 'demo', title: 'Subtitled video', formats: [],+ subtitles: {+ en: [{ ext: 'vtt', url: 'https://example.com/en.vtt?token=private', name: 'English' }, { ext: 'srt', url: 'https://example.com/en.srt' }],+ live_chat: [{ ext: 'json', url: 'https://example.com/chat' }],+ fr: [{ ext: 'vtt' }],+ de: [{ ext: 'vtt', url: 'file:///tmp/captions' }]+ },+ automatic_captions: { en: [{ ext: 'vtt', url: 'https://example.com/auto.vtt' }], 'zh-Hans': [{ ext: 'srt', url: 'https://example.com/zh.srt' }] }+ }, 'https://youtu.be/demo');+ expect(probe.options).toEqual([+ { id: 'subtitle-manual-en', mediaType: 'subtitle', container: 'srt', subtitleLanguage: 'en', subtitleName: 'English', subtitleSource: 'manual' },+ { id: 'subtitle-automatic-en', mediaType: 'subtitle', container: 'srt', subtitleLanguage: 'en', subtitleSource: 'automatic' },+ { id: 'subtitle-automatic-zh-Hans', mediaType: 'subtitle', container: 'srt', subtitleLanguage: 'zh-Hans', subtitleSource: 'automatic' }+ ]);+ expect(JSON.stringify(probe)).not.toContain('private');+ });++ it.each(['manual', 'automatic'] as const)('downloads only the selected %s subtitle track and validates SRT', async source => {+ const binaries = await fakeBinaries();+ const executor = createDownloadExecutor(binaries);+ const workdir = join(tempDir, 'subtitle-work');+ await mkdir(workdir);+ const sourceUrl = 'https://youtu.be/demo';+ const option = { id: `subtitle-${source}-en`, mediaType: 'subtitle' as const, container: 'srt' as const, subtitleLanguage: 'en', subtitleSource: source };+ const probe = parseDownloadProbe({ id: 'demo', title: 'Subtitle video', formats: [] }, sourceUrl);+ probe.options = [option];+ const result = await executor.run(stageInput({+ workdir, stageId: 'download', state: { sourceUrl, selectedOptionId: option.id, mediaType: 'subtitle' },+ inputArtifacts: [await writeProbeArtifact(workdir, probe)]+ }));+ const args = JSON.parse(await readFile(join(workdir, 'args.json'), 'utf8')) as string[];+ expect(args).toEqual(expect.arrayContaining(['--skip-download', '--sub-langs', '^en$', '--convert-subs', 'srt', '--ffmpeg-location', binaries.ffmpegPath, '--proxy', 'http://127.0.0.1:7897']));+ expect(args).toContain(source === 'automatic' ? '--write-auto-subs' : '--write-subs');+ expect(args).not.toContain(source === 'automatic' ? '--write-subs' : '--write-auto-subs');+ expect(result.outputs[0]).toMatchObject({ kind: 'source_subtitle', status: 'completed', metadata: { optionId: option.id, subtitleLanguage: 'en', subtitleSource: source, cueCount: 1, mimeType: 'application/x-subrip' } });+ expect(await readFile(result.outputs[0]!.path!, 'utf8')).toContain('Hello subtitles');+ });+it('downloads the queued draft source even if the URL changes before execution', async () => {const executor = createDownloadExecutor(await fakeBinaries());const workdir = join(tempDir, 'draft-preview');@@ -1556,6 +1611,7 @@ async function fakeBinaries(input?: {outputName?: string;reportedOutputName?: string;splitOutputUtf8?: boolean;+ subtitleContent?: string | null;}): Promise<{configStore: {read(): Promise<ReturnType<typeof createDefaultCreatorServicesConfig>>;@@ -1600,6 +1656,12 @@ if (args.includes('--dump-single-json')) {}));process.exit(0);}+if (args.includes('--skip-download')) {+ const template = args[args.indexOf('-o') + 1];+ const subtitle = ${JSON.stringify(input?.subtitleContent === undefined ? '1\n00:00:00,000 --> 00:00:01,000\nHello subtitles\n' : input.subtitleContent)};+ if (subtitle !== null) writeFileSync(template.replace('%(title).120B', 'Subtitle video').replace('%(id)s', 'demo').replace('%(ext)s', 'en.srt'), subtitle);+ process.exit(0);+}const audio = args.includes('--extract-audio');const output = join(process.cwd(), ${JSON.stringify(input?.outputName ?? null)} ?? (audio ? 'download.mp3' : 'download.mp4'));const reportedOutput = join(process.cwd(), ${JSON.stringify(input?.reportedOutputName ?? null)} ?? ${JSON.stringify(input?.outputName ?? null)} ?? (audio ? 'download.mp3' : 'download.mp4'));diff --git a/apps/daemon/test/unit/creator-krillin-cli-protocol.test.ts b/apps/daemon/test/unit/creator-krillin-cli-protocol.test.tsindex 9dea8ef1..306816de 100644--- a/apps/daemon/test/unit/creator-krillin-cli-protocol.test.ts+++ b/apps/daemon/test/unit/creator-krillin-cli-protocol.test.ts@@ -13,6 +13,23 @@ import { createKrillinConfigToml } from '../../src/creator/krillin/config-bridgeimport { buildKrillinStageOptions, normalizeKrillinFailure } from '../../src/creator/krillin/adapter.js';describe('KrillinAI CLI protocol', () => {+ it('translates a standalone SRT without passing an old video or translated import', () => {+ const stage = { job: { templateId: 'video-translation', state: { sourceType: 'subtitle', sourceUrl: 'https://youtu.be/old', sourceLanguage: 'en', targetLanguage: 'zh_cn' } }, stageRun: { stageId: 'subtitle', id: 'stage' }, workdir: '/job/stage' };+ const args = buildKrillinCliCommandArguments(stage as never, [+ { id: 'srt', kind: 'source_subtitle', path: '/job/source.srt' },+ { id: 'old', kind: 'source_video', path: '/job/old.mp4' },+ { id: 'old-target', kind: 'target_subtitle', path: '/job/old-target.srt' }+ ], buildKrillinStageOptions(stage as never), undefined, 'https://youtu.be/old');+ expect(args.slice(0, 2)).toEqual(['subtitle', '--origin-lang']);+ expect(args).toContain('/job/source.srt');+ expect(args).toContain('--srt-translated=false');+ expect(args).not.toContain('--prepare-video');+ expect(args).not.toContain('/job/old.mp4');+ expect(args).not.toContain('/job/old-target.srt');+ expect(args).not.toContain('https://youtu.be/old');+ expect(() => buildKrillinCliCommandArguments(stage as never, [], buildKrillinStageOptions(stage as never), undefined))+ .toThrow('imported source SRT');+ });it.each(['audio_no_speech', 'audio_transcription_empty', 'audio_transcription_invalid_response', 'audio_transcription_timestamps_missing', 'audio_transcription_api_failed'])('preserves %s through usage-error normalization', code => {const message = 'OpenAI transcription response was classified by the runtime';expect(normalizeKrillinFailure({ code, kind: 'usage', message })).toEqual({ code, message });diff --git a/apps/daemon/test/unit/creator-preflight.test.ts b/apps/daemon/test/unit/creator-preflight.test.tsindex 5700f9ad..c6dc98b5 100644--- a/apps/daemon/test/unit/creator-preflight.test.ts+++ b/apps/daemon/test/unit/creator-preflight.test.ts@@ -21,6 +21,35 @@ afterEach(async () => {});describe('creator preflight', () => {+ it('requires an SRT input but no transcription credentials for subtitle-only tasks', async () => {+ root = await mkdtemp(join(tmpdir(), 'creator-srt-preflight-'));+ const path = join(root, 'source.srt');+ await writeFile(path, '1\n00:00:02,250 --> 00:00:04,750\nHello\n');+ const config = createDefaultCreatorServicesConfig();+ config.llm.source = 'custom';+ config.llm.baseUrl = 'https://example.test/v1';+ config.llm.apiKey = 'test-translation-key';+ config.llm.model = 'test-translation-model';+ config.transcription.provider = 'openai';+ config.transcription.openai.apiKey = '';+ const job = fakeJob('video-translation', { sourceType: 'subtitle', sourceUrl: 'https://www.bilibili.com/video/BV18E421w7bf', preferPlatformCaptions: false });+ const get = vi.fn();+ const preflight = createCreatorPreflight({ configStore: { read: async () => config },+ readCapabilities: () => createKrillinCreatorServicesCapabilities('darwin', 'arm64'),+ resourceRoot: root, jobsRoot: join(root, 'jobs'), executorIds: ['krillinai'],+ validateRuntimeAssets: false, videoMetadataService: { get }+ });+ const stage = createVideoTranslationTemplate().stages.find(stage => stage.id === 'subtitle')!;+ expect((await preflight.check(job, stage)).blocked).toContainEqual(expect.objectContaining({ id: 'input-subtitle' }));+ job.state.importedSourceSubtitleId = 'source-srt';+ job.artifacts = [{ id: 'source-srt', jobId: job.id, kind: 'source_subtitle', version: 1, status: 'completed', path,+ scopeKey: null, inputFingerprint: null, sha256: null, sourceArtifactIds: [], metadata: {}, createdAt: job.createdAt }];+ const result = await preflight.check(job, stage);+ expect(result.blocked).toEqual([]);+ expect(result.canStart).toBe(true);+ expect(get).not.toHaveBeenCalled();+ expect([...result.ready, ...result.blocked].map(item => item.id)).not.toContain('transcription-config');+ });it('blocks multiple official Stickman references before submitting any generation', async () => {root = await mkdtemp(join(tmpdir(), 'creator-official-references-'));const config = createDefaultCreatorServicesConfig();diff --git a/apps/web/e2e/video-download-layout.spec.ts b/apps/web/e2e/video-download-layout.spec.tsindex 33c14b1f..1ddef898 100644--- a/apps/web/e2e/video-download-layout.spec.ts+++ b/apps/web/e2e/video-download-layout.spec.ts@@ -1,6 +1,54 @@import type { CreatorJob } from '@opencreator/protocol';import { expect, test } from './fixtures/runtime.js';+test('available subtitles appear beside video and audio with language and caption source', async ({ page, runtime }, testInfo) => {+ const sourceUrl = 'https://www.youtube.com/watch?v=subtitle-demo';+ const { job } = await runtime.api<{ job: CreatorJob }>('POST', '/creator/jobs', {+ projectId: runtime.projectId, templateId: 'video-download', creationKey: 'subtitle-layout', state: { sourceUrl }+ });+ const probe: CreatorJob['artifacts'][number] = {+ id: 'subtitle-probe', jobId: job.id, kind: 'download_probe', status: 'completed', version: 1,+ path: null, scopeKey: null, inputFingerprint: null, sha256: null, sourceArtifactIds: [], createdAt: new Date().toISOString(),+ metadata: {+ id: 'subtitle-demo', title: 'YouTube subtitle demo', requestedUrl: sourceUrl, url: sourceUrl, platform: 'youtube',+ uploader: 'OpenCreator', thumbnailUrl: null, duration: 90, width: 1920, height: 1080, formats: [],+ options: [+ { id: 'video-1080', mediaType: 'video', container: 'mp4', height: 1080 },+ { id: 'audio-mp3', mediaType: 'audio', container: 'mp3', bitrateKbps: 192 },+ { id: 'subtitle-manual-en', mediaType: 'subtitle', container: 'srt', subtitleLanguage: 'en', subtitleName: 'English', subtitleSource: 'manual' },+ { id: 'subtitle-automatic-zh-Hans', mediaType: 'subtitle', container: 'srt', subtitleLanguage: 'zh-Hans', subtitleName: 'Chinese (Simplified)', subtitleSource: 'automatic' }+ ]+ }+ };+ await page.route(`**/creator/jobs/${job.id}`, async route => {+ if (route.request().method() === 'GET') await route.fulfill({ json: { job: { ...job, artifacts: [probe] } } });+ else await route.continue();+ });+ await page.addInitScript(({ projectId, threadId }) => {+ localStorage.setItem('opencreator.preferences.dynamicBackground', 'false');+ localStorage.setItem('opencreator.preferences.language', 'zh-CN');+ localStorage.setItem('opencreator.navigation.v3', JSON.stringify({ currentProjectId: projectId, selectedThreadId: threadId }));+ }, { projectId: runtime.projectId, threadId: runtime.ordinaryThreadId });+ await page.goto(`${runtime.origin}/#/workbench?tool=video-download&jobId=${encodeURIComponent(job.id)}`);+ await page.getByRole('button', { name: '稍后配置,进入本地模式' }).click();+ await expect(page.getByRole('tab', { name: 'MP4 视频' })).toBeVisible();+ await expect(page.getByRole('tab', { name: 'MP3 音频' })).toBeVisible();+ const subtitles = page.getByRole('tab', { name: 'SRT 字幕' });+ await subtitles.click();+ await expect(subtitles).toHaveAttribute('aria-selected', 'true');+ await expect(page.getByText('SRT · 人工字幕 · en')).toBeVisible();+ await expect(page.getByText('SRT · 自动字幕 · zh-Hans')).toBeVisible();+ await expect(page.getByRole('button', { name: '下载 English' })).toBeEnabled();+ await expect(page.getByRole('button', { name: '下载 Chinese (Simplified)' })).toBeEnabled();+ await expect(page.getByRole('tab', { name: 'MP4 视频' })).toHaveAttribute('aria-selected', 'false');+ const tabStyles = await page.getByRole('tablist', { name: '下载格式' }).evaluate(element => [...element.querySelectorAll('button')].map(button => ({+ label: button.textContent, selected: button.getAttribute('aria-selected'), background: getComputedStyle(button).backgroundColor+ })));+ await testInfo.attach('download-tab-styles', { body: JSON.stringify(tabStyles, null, 2), contentType: 'application/json' });+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);+ await page.screenshot({ path: testInfo.outputPath('video-download-subtitles.png'), fullPage: true, animations: 'disabled' });+});+test('video download platforms stay centered and wrap within the full workspace width', async ({ page, runtime }, testInfo) => {const { job } = await runtime.api<{ job: CreatorJob }>('POST', '/creator/jobs', {projectId: runtime.projectId,diff --git a/apps/web/e2e/video-translation-subtitle-only.spec.ts b/apps/web/e2e/video-translation-subtitle-only.spec.tsnew file mode 100644index 00000000..84887b8c--- /dev/null+++ b/apps/web/e2e/video-translation-subtitle-only.spec.ts@@ -0,0 +1,80 @@+import type { CreatorJob } from '@opencreator/protocol';+import { expect, test } from './fixtures/runtime.js';++test('standalone SRT uses two steps and opens an editable result without video', async ({ page, runtime }, testInfo) => {+ const { job } = await runtime.api<{ job: CreatorJob }>('POST', '/creator/jobs', {+ projectId: runtime.projectId, templateId: 'video-translation', templateVersion: 2,+ creationKey: 'standalone-srt', state: { sourceLanguage: 'en', targetLanguage: 'zh_cn' }+ });+ await page.addInitScript(({ projectId, threadId }) => {+ localStorage.setItem('opencreator.preferences.dynamicBackground', 'false');+ localStorage.setItem('opencreator.preferences.language', 'zh-CN');+ localStorage.setItem('opencreator.navigation.v3', JSON.stringify({ currentProjectId: projectId, selectedThreadId: threadId }));+ }, { projectId: runtime.projectId, threadId: runtime.ordinaryThreadId });+ await page.goto(`${runtime.origin}/#/workbench?tool=video-translation&jobId=${encodeURIComponent(job.id)}`);+ await page.getByRole('button', { name: '稍后配置,进入本地模式' }).click();+ const creatorTab = page.getByRole('tab', { name: '创作', exact: true });+ if (await creatorTab.isVisible()) await creatorTab.click();+ const workspace = page.getByRole('region', { name: '视频翻译操作区' });+ await workspace.getByRole('tab', { name: '翻译字幕', exact: true }).click();+ await expect(workspace.getByRole('navigation', { name: '翻译流程' }).locator('li')).toHaveCount(2);+ await workspace.getByLabel('UTF-8 SRT 文件').setInputFiles({+ name: 'lecture.en.srt', mimeType: 'application/x-subrip',+ buffer: Buffer.from('1\n00:00:02,250 --> 00:00:04,750\nWelcome to OpenCreator.\n\n2\n00:00:05,000 --> 00:00:07,500\nKeep the original timeline.\n')+ });+ await expect(workspace.getByText(/本地导入 · lecture.en.srt/)).toBeVisible();+ await expect(workspace.locator('.video-translation-subtitle-import pre')).toBeVisible();+ await expect(workspace.locator('.video-translation-subtitle-import pre')).toContainText('Welcome to OpenCreator.');+ await expect(workspace.locator('.video-translation-subtitle-import pre')).toContainText('00:00:02,250');+ await workspace.getByRole('button', { name: '继续', exact: true }).click();+ await expect(workspace.getByRole('button', { name: '开始翻译', exact: true })).toBeVisible();+ await expect(workspace.getByRole('switch', { name: '优先使用平台字幕' })).toHaveCount(0);+ await expect(workspace.getByRole('button', { name: /视频与字幕/ })).toHaveCount(0);+ await expect.poll(async () => (await runtime.api<{ job: CreatorJob }>('GET', `/creator/jobs/${job.id}`)).job.state.currentStep).toBe(1);+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);+ await page.screenshot({ path: testInfo.outputPath('subtitle-only-settings.png'), fullPage: true, animations: 'disabled' });+ await page.reload();+ await page.getByRole('button', { name: '稍后配置,进入本地模式' }).click();+ if (await creatorTab.isVisible()) await creatorTab.click();+ await expect(workspace.getByRole('button', { name: '开始翻译', exact: true })).toBeVisible();+ const saved = (await runtime.api<{ job: CreatorJob }>('GET', `/creator/jobs/${job.id}`)).job;+ expect(saved.state.sourceType).toBe('subtitle');+ expect(saved.stages).toHaveLength(0);+ const source = saved.artifacts.find(artifact => artifact.id === saved.state.importedSourceSubtitleId)!;+ const target = { ...source, id: 'translated-srt', kind: 'target_subtitle', metadata: {+ resultVersion: 2, fileName: 'lecture.zh.srt', cues: [+ { id: 1, start: '00:00:02,250', end: '00:00:04,750', text: '欢迎使用 OpenCreator。' },+ { id: 2, start: '00:00:05,000', end: '00:00:07,500', text: '保留原始时间轴。' }+ ]+ } };+ const bilingual = { ...target, id: 'bilingual-srt', kind: 'bilingual_subtitle', metadata: { ...target.metadata, fileName: 'lecture.bilingual.srt' } };+ const completed: CreatorJob = { ...saved, revision: saved.revision + 1, status: 'completed', artifacts: [...saved.artifacts, target, bilingual], state: {+ ...saved.state, resultVersion: 2, workspacePhase: 'result', resultSnapshots: [{+ version: 2, createdAt: saved.updatedAt, action: 'stage-succeeded', stageId: 'subtitle', description: '字幕翻译',+ artifactRefs: { source_subtitle: [source.id], target_subtitle: [target.id], bilingual_subtitle: [bilingual.id] },+ changedArtifactIds: [target.id, bilingual.id], staleArtifactIds: [], state: saved.state+ }]+ } };+ await page.route(`**/creator/jobs/${job.id}`, route => route.request().method() === 'GET'+ ? route.fulfill({ json: { job: completed } }) : route.continue());+ await page.route(`**/creator/jobs/${job.id}/artifacts/${target.id}/content`, route => route.fulfill({+ contentType: 'application/x-subrip', body: '1\n00:00:02,250 --> 00:00:04,750\n欢迎使用 OpenCreator。\n'+ }));+ await page.reload();+ await page.getByRole('button', { name: '稍后配置,进入本地模式' }).click();+ if (await creatorTab.isVisible()) await creatorTab.click();+ await expect(workspace.getByRole('tab', { name: '字幕', exact: true })).toHaveAttribute('aria-selected', 'true');+ await expect(workspace.getByRole('textbox', { name: '字幕原文 1', exact: true })).toHaveValue('Welcome to OpenCreator.');+ await expect(workspace.getByRole('textbox', { name: '字幕 1', exact: true })).toHaveValue('欢迎使用 OpenCreator。');+ await expect(workspace.locator('video')).toHaveCount(0);+ await expect(workspace.getByRole('tab', { name: '作品', exact: true })).toHaveCount(0);+ await expect(workspace.getByRole('tab', { name: '配音', exact: true })).toHaveCount(0);+ await expect(workspace.getByRole('button', { name: '双语 SRT' })).toBeEnabled();+ const downloadEvent = page.waitForEvent('download');+ await workspace.getByRole('button', { name: '译文 SRT' }).click();+ expect((await downloadEvent).suggestedFilename()).toBe('lecture.zh.srt');+ await workspace.getByRole('textbox', { name: '字幕 1', exact: true }).fill('欢迎使用 OpenCreator 字幕翻译。');+ await expect(workspace.getByRole('button', { name: '保存字幕', exact: true })).toBeEnabled();+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);+ await page.screenshot({ path: testInfo.outputPath('subtitle-only-editor.png'), fullPage: true, animations: 'disabled' });+});diff --git a/apps/web/src/features/dashboard/VideoDownloadWorkspace.test.tsx b/apps/web/src/features/dashboard/VideoDownloadWorkspace.test.tsxindex c7b622eb..243baf35 100644--- a/apps/web/src/features/dashboard/VideoDownloadWorkspace.test.tsx+++ b/apps/web/src/features/dashboard/VideoDownloadWorkspace.test.tsx@@ -11,6 +11,10 @@ import { act, fireEvent, render, screen, waitFor, within } from '@testing-librarimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { useEffect } from 'react';import { LanguageProvider } from '../../i18n/LanguageProvider.js';+import type { AppLanguage } from '../../i18n/language.js';+import { appLanguageOptions } from '../../i18n/language.js';+import { createLocalizedCopy } from '../../i18n/localized-copy.js';+import { LanguageSwitchControls } from '../../test/LanguageSwitchControls.js';import { CreatorSessionProvider, useOptionalCreatorSession } from './creator-session-store.js';import VideoDownloadWorkspace from './VideoDownloadWorkspace.js';import type { RuntimeDependenciesController } from '../../app/use-runtime-dependencies.js';@@ -46,6 +50,95 @@ afterEach(() => {});describe('VideoDownloadWorkspace', () => {+ it('localizes subtitle provenance and reorders tracks when the display language changes', () => {+ const probe = probeArtifact();+ const tracks = ['en', ...appLanguageOptions.filter(option => option.value !== 'en-US').map(option => option.value)];+ (probe.metadata.options as CreatorJson[]).push(...tracks.map((track, index) => ({+ id: `subtitle-${index}`, mediaType: 'subtitle', container: 'srt', subtitleLanguage: track, subtitleName: track,+ subtitleSource: index % 2 === 0 ? 'manual' : 'automatic'+ })));+ render(<LanguageProvider initialPreference="zh-CN"><LanguageSwitchControls /><CreatorSessionProvider+ initialJob={job({ state: { sourceUrl: 'https://www.youtube.com/watch?v=demo' }, artifacts: [probe] })}+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}>+ <VideoDownloadWorkspace onBack={vi.fn()} />+ </CreatorSessionProvider></LanguageProvider>);+ fireEvent.click(screen.getByRole('tab', { name: /SRT/ }));+ for (const { value: language } of appLanguageOptions) {+ fireEvent.click(screen.getByRole('button', { name: language }));+ const l = createLocalizedCopy(language);+ expect(screen.getByRole('tab', { name: `SRT ${l('字幕', 'Subtitles')}` })).toHaveAttribute('aria-selected', 'true');+ expect(screen.getByText(`SRT · ${l('人工字幕', 'Manual subtitles')} · en`)).toBeVisible();+ expect(screen.getByText(`SRT · ${l('自动字幕', 'Automatic captions')} · zh-CN`)).toBeVisible();+ const promoted = language === 'en-US' ? ['en'] : ['en', language];+ expect(screen.getAllByRole('radio').map(radio => radio.closest('label')?.querySelector('strong')?.textContent))+ .toEqual([...promoted, ...tracks.filter(track => !promoted.includes(track))]);+ }+ });++ it.each<{+ language: AppLanguage;+ tracks: string[];+ expected: string[];+ }>([+ { language: 'zh-CN', tracks: ['fr', 'zh-Hant', 'ja', 'en', 'de', 'zh-Hans', 'en-US'], expected: ['en', 'zh-Hans', 'fr', 'zh-Hant', 'ja', 'de', 'en-US'] },+ { language: 'en-US', tracks: ['fr', 'zh', 'en-US', 'de', 'en'], expected: ['en-US', 'fr', 'zh', 'de', 'en'] },+ { language: 'fr-FR', tracks: ['ja', 'de', 'fr', 'en-orig', 'zh'], expected: ['en-orig', 'fr', 'ja', 'de', 'zh'] },+ { language: 'ja-JP', tracks: ['fr', 'en', 'de'], expected: ['en', 'fr', 'de'] },+ { language: 'zh-CN', tracks: ['fr', 'zh', 'de'], expected: ['zh', 'fr', 'de'] },+ { language: 'ja-JP', tracks: ['fr', 'de'], expected: ['fr', 'de'] }+ ])('prioritizes English and $language subtitles while preserving the remaining order: $tracks', async ({ language, tracks, expected }) => {+ const probe = probeArtifact();+ (probe.metadata.options as CreatorJson[]).push(...tracks.map((track, index) => ({+ id: `subtitle-${index}`, mediaType: 'subtitle', container: 'srt', subtitleLanguage: track, subtitleName: track,+ subtitleSource: index % 2 === 0 ? 'manual' : 'automatic'+ })));+ renderWorkspace(job({ state: { sourceUrl: 'https://www.youtube.com/watch?v=demo' }, artifacts: [probe] }), { applyAction: vi.fn(), language });+ fireEvent.click(await screen.findByRole('tab', { name: /SRT/ }));+ const radios = screen.getAllByRole('radio');+ expect(radios.map(radio => radio.closest('label')?.querySelector('strong')?.textContent)).toEqual(expected);+ expect(radios[0]).toBeChecked();+ expect((probe.metadata.options as Array<{ subtitleLanguage?: string }>).filter(option => option.subtitleLanguage).map(option => option.subtitleLanguage)).toEqual(tracks);+ });++ it('shows the subtitle tab only when the probe includes subtitle tracks and queues the selected SRT', async () => {+ const probe = probeArtifact();+ (probe.metadata.options as CreatorJson[]).push({+ id: 'subtitle-manual-en', mediaType: 'subtitle', container: 'srt', subtitleLanguage: 'en', subtitleName: 'English', subtitleSource: 'manual'+ }, {+ id: 'subtitle-automatic-zh', mediaType: 'subtitle', container: 'srt', subtitleLanguage: 'zh', subtitleName: '中文', subtitleSource: 'automatic'+ });+ const current = job({ state: { sourceUrl: 'https://www.youtube.com/watch?v=demo' }, artifacts: [probe] });+ const applyAction = vi.fn();+ renderWorkspace(current, { applyAction });+ const tab = await screen.findByRole('tab', { name: 'SRT 字幕' });+ fireEvent.click(tab);+ expect(tab).toHaveAttribute('aria-selected', 'true');+ expect(screen.getByText('SRT · 人工字幕 · en')).toBeInTheDocument();+ expect(screen.getByText('SRT · 自动字幕 · zh')).toBeInTheDocument();+ expect(screen.queryByRole('combobox', { name: '音频语言' })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: '下载 中文' }));+ await waitFor(() => expect(applyAction).toHaveBeenCalledWith(current.id, expect.objectContaining({+ action: 'run-stage', input: { stageId: 'download', optionId: 'subtitle-automatic-zh', mediaType: 'subtitle', sourceUrl: 'https://www.youtube.com/watch?v=demo' }+ })));+ });++ it('hides the subtitle tab when no subtitles are available', async () => {+ renderWorkspace(job({ state: { sourceUrl: 'https://www.youtube.com/watch?v=demo' }, artifacts: [probeArtifact()] }), { applyAction: vi.fn() });+ await screen.findByRole('heading', { name: 'Creator Download' });+ expect(screen.queryByRole('tab', { name: 'SRT 字幕' })).not.toBeInTheDocument();+ });++ it('shows downloaded SRT files with a save action and without a video playback action', async () => {+ const subtitle = { ...probeArtifact(), id: 'downloaded_subtitle', kind: 'source_subtitle', path: '/tmp/captions.en.srt', metadata: {+ fileName: 'captions.en.srt', size: 100, subtitleLanguage: 'en', subtitleSource: 'manual', mediaType: 'subtitle', optionId: 'subtitle-manual-en'+ } };+ renderWorkspace(job({ state: { sourceUrl: 'https://www.youtube.com/watch?v=demo' }, artifacts: [probeArtifact(), subtitle] }), { applyAction: vi.fn() });+ fireEvent.click(await screen.findByRole('tab', { name: /作品/ }));+ expect(screen.getByText('captions.en.srt')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: '保存到本机 captions.en.srt' })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: '预览视频 captions.en.srt' })).not.toBeInTheDocument();+ });+it('downloads the current thumbnail as an image and disables repeated clicks until it is ready', async () => {const current = job({ state: { sourceUrl: 'https://www.youtube.com/watch?v=demo' }, artifacts: [probeArtifact()] });let finish!: (response: Response) => void;@@ -871,6 +964,7 @@ function renderWorkspace(runtimeDependencies?: Partial<RuntimeDependenciesController>;onOpenRuntimeComponents?: () => void;onSnapshot?: (callback: (next: CreatorJob) => void) => void;+ language?: AppLanguage;}) {const runtimeDependencies = input.runtimeDependencies === undefined@@ -882,7 +976,7 @@ function renderWorkspace(...input.runtimeDependencies} as RuntimeDependenciesController;return render(- <LanguageProvider initialPreference="zh-CN">+ <LanguageProvider initialPreference={input.language ?? 'zh-CN'}><CreatorSessionProviderinitialJob={initialJob}service={{diff --git a/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx b/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsxindex 1119c4ef..e2731068 100644--- a/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx+++ b/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx@@ -22,10 +22,12 @@ import {PackageOpen,Play,RefreshCw,+ Subtitles,Video,XCircle} from 'lucide-react';import { Fragment, useEffect, useMemo, useRef, useState } from 'react';+import { useAppLanguage } from '../../i18n/LanguageProvider.js';import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';import NativeSelect from '../../components/forms/NativeSelect.js';import CreatorTaskSummary from './CreatorTaskSummary.js';@@ -62,10 +64,11 @@ export default function VideoDownloadWorkspace(props: {batch?: VideoDownloadBatchView;}) {const l = useLocalizedCopy();+ const { language } = useAppLanguage();const session = useOptionalCreatorSession();const [url, setUrl] = useState(() => readString(session?.state.sourceUrl) ?? '');const [mediaType, setMediaType] = useState<DownloadMediaType>(- () => session?.state.mediaType === 'audio' ? 'audio' : 'video'+ () => session?.state.mediaType === 'subtitle' ? 'subtitle' : session?.state.mediaType === 'audio' ? 'audio' : 'video');const [selectedOptionId, setSelectedOptionId] = useState(() => readString(session?.state.selectedOptionId) ?? ''@@ -101,9 +104,13 @@ export default function VideoDownloadWorkspace(props: {[probeArtifact, props.batch?.hasSelectedSource]);const legacy = (session?.job.templateVersion ?? 2) < 2;- const options = useMemo(() => (- (probe?.options ?? []).filter(option => !legacy || option.mediaType === 'video')- ), [legacy, probe?.options]);+ const options = useMemo(() => {+ const available = (probe?.options ?? []).filter(option => !legacy || option.mediaType === 'video');+ return [+ ...available.filter(option => option.mediaType !== 'subtitle'),+ ...prioritizeSubtitleOptions(available.filter(option => option.mediaType === 'subtitle'), language)+ ];+ }, [language, legacy, probe?.options]);const selectedOption = options.find(option => option.id === selectedOptionId);const mediaOptions = options.filter(option => option.mediaType === mediaType);const audioLanguages = availableAudioLanguages(mediaOptions);@@ -119,7 +126,7 @@ export default function VideoDownloadWorkspace(props: {() => (session?.job.artifacts ?? []).filter(artifact => (artifact.status === 'completed'- && (artifact.kind === 'source_video' || artifact.kind === 'source_audio')+ && (artifact.kind === 'source_video' || artifact.kind === 'source_audio' || artifact.kind === 'source_subtitle'))).sort(compareArtifactFreshness),[session?.job.artifacts]@@ -170,7 +177,7 @@ export default function VideoDownloadWorkspace(props: {const sourceProbeArtifact = latestMatchingProbe(job.artifacts, sourceUrl);const sourceProbe = sourceProbeArtifact === undefined ? undefined : readDownloadProbe(sourceProbeArtifact.metadata);const artifacts = job.artifacts.filter(artifact => artifact.status === 'completed'- && (artifact.kind === 'source_video' || artifact.kind === 'source_audio')).sort(compareArtifactFreshness);+ && (artifact.kind === 'source_video' || artifact.kind === 'source_audio' || artifact.kind === 'source_subtitle')).sort(compareArtifactFreshness);return downloadHistoryItems(sourceProbe?.options ?? [],job.stages.filter(stage => stage.stageId === 'download'), artifacts, sourceProbeArtifact, sourceProbe).map(item => ({ ...item, ownerJobId: job.id, sourceTitle: sourceProbe?.title ?? sourceUrl }));@@ -627,7 +634,7 @@ export default function VideoDownloadWorkspace(props: {if (stage.stageId !== 'download'|| optionId === undefined- || (mediaType !== 'video' && mediaType !== 'audio')+ || (mediaType !== 'video' && mediaType !== 'audio' && mediaType !== 'subtitle')) {throw new Error('failed download stage cannot be retried');}@@ -870,6 +877,17 @@ export default function VideoDownloadWorkspace(props: {MP3 {l('音频', 'audio')}</button>) : null}+ {!legacy && options.some(option => option.mediaType === 'subtitle') ? (+ <button+ type="button"+ role="tab"+ aria-selected={mediaType === 'subtitle'}+ onClick={() => selectMediaType('subtitle')}+ >+ <Subtitles size={15} strokeWidth={1.8} aria-hidden="true" />+ SRT {l('字幕', 'Subtitles')}+ </button>+ ) : null}</div>{audioLanguages.length > 1 && selectedAudioLanguage !== undefined ? (<label className="creator-tool-field video-download-language-field">@@ -1056,7 +1074,7 @@ export default function VideoDownloadWorkspace(props: {</span>) : (<div className="video-download-file-actions">- <button+ {artifact.kind !== 'source_subtitle' ? <buttontype="button"onClick={() => toggleArtifactPreview(artifact)}aria-label={previewOpen@@ -1075,7 +1093,7 @@ export default function VideoDownloadWorkspace(props: {: previewOpen? <ChevronUp size={16} strokeWidth={1.8} />: <Play size={16} strokeWidth={1.8} />}- </button>+ </button> : null}<buttontype="button"onClick={() => void downloadArtifact(artifact)}@@ -1237,8 +1255,8 @@ function readDownloadOption(value: CreatorJson): DownloadOption | undefined {}if (typeof value.id !== 'string'- || (value.mediaType !== 'video' && value.mediaType !== 'audio')- || !['mp4', 'mp3', 'm4a', 'webm'].includes(String(value.container))+ || (value.mediaType !== 'video' && value.mediaType !== 'audio' && value.mediaType !== 'subtitle')+ || !['mp4', 'mp3', 'm4a', 'webm', 'srt'].includes(String(value.container))) {return undefined;}@@ -1246,6 +1264,9 @@ function readDownloadOption(value: CreatorJson): DownloadOption | undefined {id: value.id,mediaType: value.mediaType,container: value.container as DownloadOption['container'],+ ...(typeof value.subtitleLanguage === 'string' ? { subtitleLanguage: value.subtitleLanguage } : {}),+ ...(typeof value.subtitleName === 'string' ? { subtitleName: value.subtitleName } : {}),+ ...(value.subtitleSource === 'manual' || value.subtitleSource === 'automatic' ? { subtitleSource: value.subtitleSource } : {}),...(readString(value.audioLanguage) === undefined? {}: { audioLanguage: readString(value.audioLanguage) }),@@ -1451,6 +1472,7 @@ function downloadPhaseLabel(function downloadHistoryIcon(item: DownloadHistoryItem) {if (item.artifact !== undefined) {+ if (item.artifact.kind === 'source_subtitle') return <Subtitles size={18} strokeWidth={1.7} />;return item.artifact.kind === 'source_audio'? <FileAudio size={18} strokeWidth={1.7} />: <FileVideo size={18} strokeWidth={1.7} />;@@ -1477,6 +1499,9 @@ function optionLabel(const prefix = option.playlistIndex === undefined? '': `${l('视频', 'Video')} ${option.playlistIndex} · `;+ if (option.mediaType === 'subtitle') {+ return `${prefix}${option.subtitleName ?? audioLanguageLabel(option.subtitleLanguage ?? 'und', l)}`;+ }if (option.mediaType === 'audio') {return `${prefix}${option.bitrateKbps ?? 192}kbps`;}@@ -1489,6 +1514,10 @@ function optionDetail(l: ReturnType<typeof useLocalizedCopy>): string {const parts = [option.container.toUpperCase()];+ if (option.mediaType === 'subtitle') {+ parts.push(option.subtitleSource === 'automatic' ? l('自动字幕', 'Automatic captions') : l('人工字幕', 'Manual subtitles'));+ if (option.subtitleLanguage !== undefined) parts.push(option.subtitleLanguage);+ }if (option.width !== undefined && option.height !== undefined) {parts.push(`${option.width} x ${option.height}`);}@@ -1505,7 +1534,11 @@ function artifactDescription(l: ReturnType<typeof useLocalizedCopy>): string {const parts = [- artifact.kind === 'source_audio' ? 'MP3' : 'MP4',+ artifact.kind === 'source_subtitle' ? 'SRT' : artifact.kind === 'source_audio' ? 'MP3' : 'MP4',+ readString(artifact.metadata.subtitleLanguage) === undefined ? undefined+ : audioLanguageLabel(readString(artifact.metadata.subtitleLanguage)!, l),+ artifact.kind !== 'source_subtitle' ? undefined : artifact.metadata.subtitleSource === 'automatic'+ ? l('自动字幕', 'Automatic captions') : l('人工字幕', 'Manual subtitles'),readNumber(artifact.metadata.size) === undefined? undefined: formatBytes(readNumber(artifact.metadata.size)!),@@ -1524,6 +1557,29 @@ function artifactDescription(return parts.filter(Boolean).join(' · ');}+function prioritizeSubtitleOptions(options: DownloadOption[], language: string): DownloadOption[] {+ const appLocale = subtitleLocale(language);+ const english = options.findIndex(option => subtitleLocale(option.subtitleLanguage)?.language === 'en');+ const localized = appLocale === undefined || appLocale.language === 'en' ? -1 : options.findIndex(option => {+ const locale = subtitleLocale(option.subtitleLanguage);+ return locale?.language === appLocale.language && locale.script === appLocale.script;+ });+ const promoted = [english, localized].filter(index => index >= 0);+ return [+ ...promoted.map(index => options[index]!),+ ...options.filter((_option, index) => !promoted.includes(index))+ ];+}++function subtitleLocale(language: string | undefined): Intl.Locale | undefined {+ if (language === undefined) return undefined;+ try {+ return new Intl.Locale(language.trim().replaceAll('_', '-').replace(/-orig$/i, '')).maximize();+ } catch {+ return undefined;+ }+}+function availableAudioLanguages(options: DownloadOption[]): string[] {const languages = new Map<string, string>();for (const option of options) {diff --git a/apps/web/src/features/dashboard/VideoTranslationResultWorkspace.tsx b/apps/web/src/features/dashboard/VideoTranslationResultWorkspace.tsxindex 064fa607..3e710637 100644--- a/apps/web/src/features/dashboard/VideoTranslationResultWorkspace.tsx+++ b/apps/web/src/features/dashboard/VideoTranslationResultWorkspace.tsx@@ -89,6 +89,8 @@ const resultTabs: Array<{];export default function VideoTranslationResultWorkspace(props: {+ subtitleOnly?: boolean;+ subtitleDownloads?: Array<{ artifactId: string; label: string }>;activeTab: VideoTranslationResultTab;version: number;versions: VersionItem[];@@ -136,6 +138,8 @@ export default function VideoTranslationResultWorkspace(props: {? 'horizontal': availableSubtitleVariants[0];const activeSubtitleOutput = props.subtitleOutputs.find(output => output.variant === activeSubtitleVariant);+ const activeSubtitleLabel = props.subtitleOnly ? l('字幕', 'Subtitles')+ : subtitleVariantLabel(activeSubtitleOutput?.variant ?? 'horizontal', l);const activeSubtitleDirty = activeSubtitleVariant === undefined? false: props.subtitleDirtyByVariant[activeSubtitleVariant] === true;@@ -196,7 +200,7 @@ export default function VideoTranslationResultWorkspace(props: {<section className="video-result-workspace" aria-label={l('视频翻译项目产出', 'Video translation project outputs')}><div className="video-result-toolbar"><div className="video-result-tabs" role="tablist" aria-label={l('产出物类型', 'Output types')}>- {resultTabs.map(tab => {+ {resultTabs.filter(tab => !props.subtitleOnly || tab.value === 'subtitles' || tab.value === 'settings').map(tab => {const Icon = tab.icon;return (<button@@ -356,6 +360,11 @@ export default function VideoTranslationResultWorkspace(props: {</p></div><div className="video-result-pane-actions">+ {props.subtitleDownloads?.map(download => <button key={download.artifactId} type="button"+ disabled={hasSubtitleDrafts || props.subtitleSavePending}+ onClick={() => props.onExport('subtitles', download.artifactId)}>+ <Download size={15} aria-hidden="true" />{download.label}+ </button>)}{availableSubtitleVariants.length > 1 ? (<div className="video-result-subtitle-variants" role="radiogroup" aria-label={l('字幕画幅', 'Subtitle format')}>{availableSubtitleVariants.map(variant => (@@ -380,7 +389,7 @@ export default function VideoTranslationResultWorkspace(props: {<Save size={15} strokeWidth={1.8} aria-hidden="true" />{props.subtitleSavePending? l('正在保存...', 'Saving...')- : l(+ : props.subtitleOnly ? l('保存字幕', 'Save subtitles') : l(`保存${activeSubtitleOutput.variant === 'horizontal' ? '横屏' : '竖屏'}字幕`,`Save ${activeSubtitleOutput.variant === 'horizontal' ? 'horizontal' : 'vertical'} subtitles`)}@@ -389,8 +398,8 @@ export default function VideoTranslationResultWorkspace(props: {</div></header>{activeSubtitleOutput !== undefined ? (- <div className="video-result-subtitle-preview-layout">- <section className="video-result-subtitle-video" aria-label={l('同步视频预览', 'Synchronized video preview')}>+ <div className="video-result-subtitle-preview-layout" data-subtitle-only={props.subtitleOnly || undefined}>+ {!props.subtitleOnly ? <section className="video-result-subtitle-video" aria-label={l('同步视频预览', 'Synchronized video preview')}><divclassName="video-result-player-frame"data-ratio={activeSubtitleOutput.variant === 'vertical' ? '9:16' : '16:9'}@@ -459,7 +468,7 @@ export default function VideoTranslationResultWorkspace(props: {{activeSubtitleVideo?.source ? (<small>{l('当前使用原视频同步预览', 'Using the source video for synchronized preview')}</small>) : null}- </section>+ </section> : null}<section className="video-result-output-column" data-variant={activeSubtitleOutput.variant}>{activeSubtitleOutput.cues.length > 0 ? (@@ -467,8 +476,8 @@ export default function VideoTranslationResultWorkspace(props: {className="video-subtitle-editor"role="list"aria-label={l(- `${subtitleVariantLabel(activeSubtitleOutput.variant, l)}内容`,- `${subtitleVariantLabel(activeSubtitleOutput.variant, l)} content`+ `${activeSubtitleLabel}内容`,+ `${activeSubtitleLabel} content`)}>{subtitleCueGroups.map((group, groupIndex) => {@@ -510,8 +519,8 @@ export default function VideoTranslationResultWorkspace(props: {activeSubtitleOutput.variant, cue.id, event.target.value, 'sourceText')}aria-label={l(- `${subtitleVariantLabel(activeSubtitleOutput.variant, l)}原文 ${index + 1}`,- `${subtitleVariantLabel(activeSubtitleOutput.variant, l)} source ${index + 1}`+ `${activeSubtitleLabel}原文 ${index + 1}`,+ `${activeSubtitleLabel} source ${index + 1}`)}/>);@@ -528,7 +537,7 @@ export default function VideoTranslationResultWorkspace(props: {cue.id,event.target.value)}- aria-label={`${subtitleVariantLabel(activeSubtitleOutput.variant, l)} ${index + 1}`}+ aria-label={props.subtitleOnly ? `${activeSubtitleLabel} ${index + 1}` : `${subtitleVariantLabel(activeSubtitleOutput.variant, l)} ${index + 1}`}/>);return (@@ -639,8 +648,8 @@ export default function VideoTranslationResultWorkspace(props: {</header><dl className="video-result-settings"><div><dt>{l('目标语言', 'Target language')}</dt><dd>{props.targetLanguage}</dd></div>- <div><dt>{l('字幕样式', 'Subtitle style')}</dt><dd>{props.subtitleStyleLabel}</dd></div>- <div><dt>{l('配音', 'Dubbing')}</dt><dd>{props.dubbing ? l('已开启', 'Enabled') : l('未开启', 'Disabled')}</dd></div>+ {!props.subtitleOnly ? <div><dt>{l('字幕样式', 'Subtitle style')}</dt><dd>{props.subtitleStyleLabel}</dd></div> : null}+ {!props.subtitleOnly ? <div><dt>{l('配音', 'Dubbing')}</dt><dd>{props.dubbing ? l('已开启', 'Enabled') : l('未开启', 'Disabled')}</dd></div> : null}<div><dt>{l('输出内容', 'Output')}</dt><dd>{props.outputLabel}</dd></div><div><dt>{l('字幕文件', 'Subtitle files')}</dt>diff --git a/apps/web/src/features/dashboard/VideoTranslationSubtitleImport.tsx b/apps/web/src/features/dashboard/VideoTranslationSubtitleImport.tsxindex c915dc7f..a032e570 100644--- a/apps/web/src/features/dashboard/VideoTranslationSubtitleImport.tsx+++ b/apps/web/src/features/dashboard/VideoTranslationSubtitleImport.tsx@@ -1,11 +1,12 @@import { useId, useRef, useState } from 'react';+import { X } from 'lucide-react';import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';import {captureCreatorClientFailure,useOptionalCreatorSession} from './creator-session-store.js';-export function VideoTranslationSubtitleImport(props: { sourceLanguage: string; targetLanguage: string; disabled: boolean }) {+export function VideoTranslationSubtitleImport(props: { sourceLanguage: string; targetLanguage: string; disabled: boolean; sourceOnly?: boolean; onBusyChange?(busy: boolean): void }) {const l = useLocalizedCopy();const session = useOptionalCreatorSession();const [enabled, setEnabled] = useState(() => session?.job.artifacts.some(artifact => artifact.metadata.source === 'local-upload' && artifact.kind.endsWith('_subtitle')) ?? false);@@ -16,7 +17,8 @@ export function VideoTranslationSubtitleImport(props: { sourceLanguage: string;const fileInputId = useId();const fileInputRef = useRef<HTMLInputElement>(null);if (session === null) return null;- const imports = session.job.artifacts.filter(artifact => artifact.metadata.source === 'local-upload' && artifact.kind.endsWith('_subtitle'));+ const imports = session.job.artifacts.filter(artifact => artifact.metadata.source === 'local-upload'+ && (props.sourceOnly ? artifact.id === session.state.importedSourceSubtitleId : artifact.kind.endsWith('_subtitle')));async function importFile(file: File) {if (session === null) return;@@ -25,6 +27,7 @@ export function VideoTranslationSubtitleImport(props: { sourceLanguage: string;return;}setBusy(true);+ props.onBusyChange?.(true);setError('');try {const contentBase64 = await captureCreatorClientFailure(@@ -39,18 +42,19 @@ export function VideoTranslationSubtitleImport(props: { sourceLanguage: string;}));await session.applyAction({ action: 'import-subtitle', input: {- fileName: file.name, contentBase64, kind,- language: kind === 'source_subtitle' ? props.sourceLanguage : props.targetLanguage+ fileName: file.name, contentBase64, kind: props.sourceOnly ? 'source_subtitle' : kind,+ language: props.sourceOnly || kind === 'source_subtitle' ? props.sourceLanguage : props.targetLanguage} });} catch {// The session records runtime and file-read failures in the shared Agent panel.} finally {setBusy(false);+ props.onBusyChange?.(false);}}return <div className="video-translation-subtitle-import" role="group" aria-label={l('导入已有字幕', 'Import existing subtitles')}>- <div className={`video-translation-toggle-row${props.disabled ? ' is-disabled' : ''}`}>+ {!props.sourceOnly ? <div className={`video-translation-toggle-row${props.disabled ? ' is-disabled' : ''}`}><span><strong>{l('导入已有字幕', 'Import existing subtitles')}</strong><small>{l('使用本地 SRT 字幕文件', 'Use a local SRT subtitle file')}</small>@@ -66,14 +70,14 @@ export function VideoTranslationSubtitleImport(props: { sourceLanguage: string;><span /></button>- </div>- {enabled ? <fieldset className="video-translation-subtitle-import-fields video-translation-field" disabled={props.disabled || busy}>- <label><span>{l('字幕类型', 'Subtitle type')}</span>+ </div> : null}+ {enabled || props.sourceOnly ? <fieldset className="video-translation-subtitle-import-fields video-translation-field" disabled={props.disabled || busy}>+ {!props.sourceOnly ? <label><span>{l('字幕类型', 'Subtitle type')}</span><select value={kind} onChange={event => setKind(event.target.value)}><option value="source_subtitle">{l('原文字幕(跳过语音识别)', 'Source subtitles (skip transcription)')}</option><option value="target_subtitle">{l('已翻译字幕(跳过识别和翻译)', 'Translated subtitles (skip transcription and translation)')}</option></select>- </label>+ </label> : null}<div className="video-translation-subtitle-file-field"><label htmlFor={fileInputId}>{l('UTF-8 SRT 文件', 'UTF-8 SRT file')}</label><div className="video-translation-subtitle-file-picker">@@ -85,14 +89,26 @@ export function VideoTranslationSubtitleImport(props: { sourceLanguage: string;void importFile(file);}}} />- <button type="button" onClick={() => fileInputRef.current?.click()}>{l('选择文件', 'Choose file')}</button>- <span aria-live="polite">{selectedFileName || l('未选择文件', 'No file selected')}</span>+ <button type="button" onClick={() => fileInputRef.current?.click()}>{props.sourceOnly && imports.length > 0 ? l('更换文件', 'Replace file') : l('选择文件', 'Choose file')}</button>+ <span aria-live="polite">{String(imports.at(-1)?.metadata.fileName ?? '') || selectedFileName || l('未选择文件', 'No file selected')}</span>+ {props.sourceOnly && imports.length > 0 ? <button+ type="button"+ className="video-translation-subtitle-remove"+ aria-label={l('移除字幕', 'Remove subtitles')}+ title={l('移除字幕', 'Remove subtitles')}+ onClick={() => {+ setSelectedFileName('');+ setError('');+ if (fileInputRef.current) fileInputRef.current.value = '';+ session.updateDraft({ importedSourceSubtitleId: null, importedTargetSubtitleId: null });+ }}+ ><X size={16} aria-hidden="true" /></button> : null}</div></div>- <p>{l('语言沿用上方选择。仅有译文时不会生成双语字幕。', 'Uses the language selected above. A translated-only import does not generate bilingual subtitles.')}</p>+ {!props.sourceOnly ? <p>{l('语言沿用上方选择。仅有译文时不会生成双语字幕。', 'Uses the language selected above. A translated-only import does not generate bilingual subtitles.')}</p> : null}{busy ? <p role="status">{l('正在导入字幕…', 'Importing subtitles…')}</p> : null}{error ? <p role="alert">{error}</p> : null}- {imports.map(artifact => <details key={artifact.id}>+ {imports.map(artifact => <details key={artifact.id} open={props.sourceOnly}><summary>{l('本地导入', 'Local import')} · {String(artifact.metadata.fileName)} · {String(artifact.metadata.language)} · {String(artifact.metadata.cueCount)} {l('条字幕', 'cues')} · v{artifact.version}</summary><pre>{Array.isArray(artifact.metadata.cues) ? artifact.metadata.cues.map(cue => cue !== null && typeof cue === 'object' && !Array.isArray(cue) ? `${cue.start} → ${cue.end}\n${cue.text}` : '').join('\n\n') : ''}</pre></details>)}diff --git a/apps/web/src/features/dashboard/VideoTranslationWorkspace.control.test.tsx b/apps/web/src/features/dashboard/VideoTranslationWorkspace.control.test.tsxindex 821db1d7..ca8a194e 100644--- a/apps/web/src/features/dashboard/VideoTranslationWorkspace.control.test.tsx+++ b/apps/web/src/features/dashboard/VideoTranslationWorkspace.control.test.tsx@@ -8,11 +8,187 @@ import {} from '@opencreator/protocol';import { describe, expect, it, vi } from 'vitest';import { LanguageProvider } from '../../i18n/LanguageProvider.js';+import { appLanguageOptions } from '../../i18n/language.js';+import { createLocalizedCopy } from '../../i18n/localized-copy.js';import { CreatorSessionProvider, useCreatorSession } from './creator-session-store.js';import VideoTranslationWorkspace from './VideoTranslationWorkspace.js';import { LanguageSwitchControls } from '../../test/LanguageSwitchControls.js';describe('VideoTranslationWorkspace task controls', () => {+ it('localizes subtitle import controls across all languages without losing the selected file or preview', () => {+ const source = { ...subtitleArtifact(1, 'Original text'), id: 'source-srt', kind: 'source_subtitle', metadata: {+ ...subtitleArtifact(1, 'Original text').metadata, source: 'local-upload', fileName: 'lecture.en.srt', cueCount: 1+ } };+ render(<LanguageProvider initialPreference="zh-CN"><LanguageSwitchControls /><CreatorSessionProvider+ initialJob={job({ status: 'draft', revision: 0, stages: [], artifacts: [source], state: {+ sourceType: 'subtitle', sourceUrl: '', currentStep: 0, furthestStep: 0, importedSourceSubtitleId: source.id+ } })} service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}>+ <VideoTranslationWorkspace onBack={vi.fn()} />+ </CreatorSessionProvider></LanguageProvider>);+ for (const { value: language } of appLanguageOptions) {+ fireEvent.click(screen.getByRole('button', { name: language }));+ const l = createLocalizedCopy(language);+ expect(screen.getByRole('tab', { name: l('翻译视频', 'Translate video') })).toBeVisible();+ expect(screen.getByRole('tab', { name: l('翻译字幕', 'Translate subtitles') })).toHaveAttribute('aria-selected', 'true');+ expect(screen.getByRole('heading', { name: l('添加字幕', 'Add subtitles') })).toBeVisible();+ expect(screen.getByRole('button', { name: l('更换文件', 'Replace file') })).toBeEnabled();+ expect(screen.getByRole('button', { name: l('移除字幕', 'Remove subtitles') })).toHaveAttribute('title', l('移除字幕', 'Remove subtitles'));+ expect(screen.getByRole('button', { name: new RegExp(l('添加素材', 'Add source')) })).toBeVisible();+ expect(within(screen.getByRole('group', { name: l('导入已有字幕', 'Import existing subtitles') })).getByText('lecture.en.srt')).toBeVisible();+ expect(document.querySelector('.video-translation-subtitle-import pre')).toBeVisible();+ expect(document.querySelector('.video-translation-subtitle-import pre')).toHaveTextContent('Original text');+ }+ });++ it('replaces and removes the selected SRT, then allows selecting the same file again', async () => {+ const source = { ...subtitleArtifact(1, 'Original text'), id: 'original-srt', kind: 'source_subtitle', metadata: {+ ...subtitleArtifact(1, 'Original text').metadata, source: 'local-upload', fileName: 'original.srt', cueCount: 1+ } };+ let current = job({ status: 'draft', revision: 0, stages: [], artifacts: [source], state: {+ sourceType: 'subtitle', sourceUrl: '', currentStep: 0, furthestStep: 0, importedSourceSubtitleId: source.id+ } });+ const applyAction = vi.fn(async (_id: string, request: { action: string; input: Record<string, CreatorJson> }) => {+ if (request.action === 'import-subtitle') {+ const replacement = { ...source, id: `replacement-${current.revision}`, metadata: {+ ...source.metadata, fileName: String(request.input.fileName), cues: [{ id: 1, start: '00:00:00,000', end: '00:00:01,000', text: 'Replacement text' }]+ } };+ current = { ...current, revision: current.revision + 1, artifacts: [...current.artifacts, replacement],+ state: { ...current.state, importedSourceSubtitleId: replacement.id } };+ } else current = { ...current, revision: current.revision + 1, state: { ...current.state, ...request.input.patch as object } };+ return { job: current };+ });+ render(<LanguageProvider initialPreference="zh-CN"><CreatorSessionProvider initialJob={current}+ service={{ applyAction, runAgentTurn: vi.fn() } as never}>+ <VideoTranslationWorkspace onBack={vi.fn()} />+ </CreatorSessionProvider></LanguageProvider>);+ const workspace = screen.getByRole('region', { name: '视频翻译操作区' });+ expect(within(workspace).getByRole('button', { name: '更换文件' })).toBeEnabled();+ expect(workspace.querySelector('pre')).toHaveTextContent('Original text');+ const file = new File(['1\n00:00:00,000 --> 00:00:01,000\nReplacement text\n'], 'replacement.srt');+ fireEvent.change(screen.getByLabelText('UTF-8 SRT 文件'), { target: { files: [file] } });+ await waitFor(() => expect(workspace.querySelector('pre')).toHaveTextContent('Replacement text'));+ expect(workspace.querySelector('pre')).not.toHaveTextContent('Original text');+ await waitFor(() => expect(within(workspace).getByRole('button', { name: '移除字幕' })).toBeEnabled());+ fireEvent.click(within(workspace).getByRole('button', { name: '移除字幕' }));+ expect(workspace.querySelector('pre')).toBeNull();+ expect(within(workspace).getByText('未选择文件')).toBeVisible();+ expect(within(workspace).getByRole('button', { name: '选择文件' })).toBeEnabled();+ expect(within(workspace).queryByRole('button', { name: '移除字幕' })).not.toBeInTheDocument();+ await waitFor(() => expect(current.state.importedSourceSubtitleId).toBeNull());+ fireEvent.click(within(workspace).getByRole('button', { name: '继续' }));+ expect(within(workspace).getByRole('alert')).toHaveTextContent('请先添加需要翻译的 SRT 字幕');+ fireEvent.change(screen.getByLabelText('UTF-8 SRT 文件'), { target: { files: [file] } });+ await waitFor(() => expect(workspace.querySelector('pre')).toHaveTextContent('Replacement text'));+ expect(within(workspace).getByRole('button', { name: '更换文件' })).toBeInTheDocument();+ });++ it('switches from subtitles to combined video inputs and clears imported subtitle selections', async () => {+ let current = job({ status: 'draft', revision: 0, stages: [], state: {+ sourceType: 'subtitle', sourceUrl: '', currentStep: 0, furthestStep: 0,+ importedSourceSubtitleId: 'source-srt', importedTargetSubtitleId: 'target-srt'+ } });+ const applyAction = vi.fn(async (_id: string, request: { input: { patch: Record<string, CreatorJson> } }) => {+ current = { ...current, revision: current.revision + 1, state: { ...current.state, ...request.input.patch } };+ return { job: current };+ });+ render(<LanguageProvider initialPreference="zh-CN"><CreatorSessionProvider initialJob={current}+ service={{ applyAction, runAgentTurn: vi.fn() } as never}>+ <VideoTranslationWorkspace onBack={vi.fn()} />+ </CreatorSessionProvider></LanguageProvider>);+ const workspace = screen.getByRole('region', { name: '视频翻译操作区' });+ const sourceTabs = within(workspace).getByRole('tablist', { name: '素材类型' });+ expect(within(sourceTabs).getAllByRole('tab')).toHaveLength(2);+ fireEvent.click(within(sourceTabs).getByRole('tab', { name: '翻译视频' }));+ expect(within(sourceTabs).getByRole('tab', { name: '翻译视频' })).toHaveAttribute('aria-selected', 'true');+ expect(within(workspace).getByRole('button', { name: '选择本地视频' })).toBeVisible();+ expect(within(workspace).getByRole('textbox', { name: '视频链接' })).toBeVisible();+ expect(within(workspace).queryByLabelText('UTF-8 SRT 文件')).not.toBeInTheDocument();+ expect(within(workspace).getByRole('navigation', { name: '翻译流程' }).querySelectorAll('li')).toHaveLength(3);+ await waitFor(() => expect(applyAction).toHaveBeenCalledWith('job_control', expect.objectContaining({+ input: expect.objectContaining({ patch: expect.objectContaining({+ sourceType: 'url', importedSourceSubtitleId: null, importedTargetSubtitleId: null+ }) })+ })));+ });++ it('requires an imported SRT and starts directly from the second step without video settings', async () => {+ let current = job({ status: 'draft', revision: 0, stages: [], state: { sourceType: 'subtitle', sourceUrl: '', currentStep: 0, furthestStep: 0 } });+ const source = { ...subtitleArtifact(1, 'Hello'), id: 'source-srt', kind: 'source_subtitle', metadata: {+ ...subtitleArtifact(1, 'Hello').metadata, source: 'local-upload', fileName: 'source.srt', cueCount: 1+ } };+ const applyAction = vi.fn(async (_id: string, request: { action: string; input: Record<string, CreatorJson> }) => {+ if (request.action === 'import-subtitle') current = { ...current, revision: current.revision + 1, artifacts: [source], state: { ...current.state, importedSourceSubtitleId: source.id } };+ else if (request.action === 'run-stage') current = { ...current, revision: current.revision + 1, status: 'running', stages: [stage({ id: 'srt-translation', status: 'queued', dispatchStatus: 'queued', progress: {} })] };+ else current = { ...current, revision: current.revision + 1, state: { ...current.state, ...request.input.patch as object } };+ return { job: current };+ });+ const uploadSourceVideo = vi.fn();+ render(<LanguageProvider initialPreference="zh-CN"><CreatorSessionProvider initialJob={current}+ service={{ applyAction, uploadSourceVideo, runAgentTurn: vi.fn(), preflight: vi.fn(async () => ({ canStart: true, ready: [], blocked: [], warning: [] })) } as never}>+ <VideoTranslationWorkspace onBack={vi.fn()} />+ </CreatorSessionProvider></LanguageProvider>);+ const workspace = screen.getByRole('region', { name: '视频翻译操作区' });+ expect(within(workspace).getByRole('tab', { name: '翻译字幕' })).toHaveAttribute('aria-selected', 'true');+ expect(within(workspace).getByRole('navigation', { name: '翻译流程' }).querySelectorAll('li')).toHaveLength(2);+ fireEvent.click(within(workspace).getByRole('button', { name: '继续' }));+ expect(within(workspace).getByRole('alert')).toHaveTextContent('请先添加需要翻译的 SRT 字幕');+ fireEvent.change(screen.getByLabelText('UTF-8 SRT 文件'), { target: { files: [new File(['1\n00:00:00,000 --> 00:00:01,000\nHello\n'], 'source.srt')] } });+ await waitFor(() => expect(applyAction).toHaveBeenCalledWith('job_control', expect.objectContaining({ action: 'import-subtitle', input: expect.objectContaining({ kind: 'source_subtitle', fileName: 'source.srt' }) })));+ await waitFor(() => expect(within(workspace).getByRole('button', { name: '继续' })).toBeEnabled());+ const subtitlePreview = workspace.querySelector('details');+ expect(subtitlePreview).toHaveAttribute('open');+ expect(subtitlePreview?.querySelector('pre')).toBeVisible();+ expect(subtitlePreview?.querySelector('pre')).toHaveTextContent('Hello');+ expect(subtitlePreview?.querySelector('pre')).toHaveTextContent('00:00:00,000');+ fireEvent.click(within(workspace).getByRole('button', { name: '继续' }));+ expect(within(workspace).getByRole('heading', { name: '设置翻译语言' })).toBeVisible();+ expect(within(workspace).queryByRole('switch', { name: '优先使用平台字幕' })).not.toBeInTheDocument();+ expect(within(workspace).queryByRole('button', { name: /视频与字幕/ })).not.toBeInTheDocument();+ fireEvent.click(within(workspace).getByRole('button', { name: '开始翻译' }));+ await waitFor(() => expect(applyAction).toHaveBeenCalledWith('job_control', expect.objectContaining({ action: 'run-stage', input: { stageId: 'subtitle', workflow: true } })));+ expect(uploadSourceVideo).not.toHaveBeenCalled();+ expect(within(workspace).getByRole('tab', { name: '字幕' })).toHaveAttribute('aria-selected', 'true');+ expect(within(workspace).queryByRole('tab', { name: '作品' })).not.toBeInTheDocument();+ expect(within(workspace).queryByRole('tab', { name: '配音' })).not.toBeInTheDocument();+ });++ it('restores subtitle-only results with source text, downloads and no video player', () => {+ const source = { ...subtitleArtifact(1, 'Hello'), id: 'source-srt', kind: 'source_subtitle', metadata: { ...subtitleArtifact(1, 'Hello').metadata, fileName: 'source.srt', source: 'local-upload' } };+ const target = subtitleArtifact(1, '你好');+ const bilingual = { ...target, id: 'bilingual-srt', kind: 'bilingual_subtitle' };+ const initialJob = job({ status: 'completed', revision: 1, stages: [], artifacts: [source, target, bilingual], state: {+ sourceType: 'subtitle', sourceUrl: '', importedSourceSubtitleId: source.id, composeVideo: false,+ resultSnapshots: [{ version: 1, createdAt: target.createdAt, action: 'run-stage', stageId: 'subtitle', description: '字幕翻译', artifactRefs: { source_subtitle: [source.id], target_subtitle: [target.id], bilingual_subtitle: [bilingual.id] }, changedArtifactIds: [target.id, bilingual.id], staleArtifactIds: [], state: { sourceType: 'subtitle', importedSourceSubtitleId: source.id, targetLanguage: 'zh_cn', sourceLanguage: 'en', bilingual: true } }]+ } });+ render(<LanguageProvider initialPreference="zh-CN"><LanguageSwitchControls /><CreatorSessionProvider initialJob={initialJob}+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}>+ <VideoTranslationWorkspace onBack={vi.fn()} />+ </CreatorSessionProvider></LanguageProvider>);+ const workspace = screen.getByRole('region', { name: '视频翻译操作区' });+ expect(within(workspace).getByRole('textbox', { name: '字幕原文 1' })).toHaveValue('Hello');+ expect(within(workspace).getByRole('textbox', { name: '字幕 1' })).toHaveValue('你好');+ expect(within(workspace).getByRole('button', { name: '译文 SRT' })).toBeEnabled();+ expect(within(workspace).getByRole('button', { name: '双语 SRT' })).toBeEnabled();+ expect(workspace.querySelector('video')).toBeNull();+ expect(within(workspace).queryByRole('button', { name: '下载原视频并预览' })).not.toBeInTheDocument();+ fireEvent.change(within(workspace).getByRole('textbox', { name: '字幕 1' }), { target: { value: '你好世界' } });+ expect(within(workspace).getByRole('button', { name: '保存字幕' })).toBeEnabled();+ expect(within(workspace).getByRole('button', { name: '译文 SRT' })).toBeDisabled();+ expect(within(workspace).queryByRole('button', { name: /保存并生成/ })).not.toBeInTheDocument();+ fireEvent.click(within(workspace).getByRole('tab', { name: '任务设置' }));+ expect(within(workspace).queryByText('字幕样式')).not.toBeInTheDocument();+ expect(within(workspace).queryByText('配音')).not.toBeInTheDocument();+ fireEvent.click(within(workspace).getByRole('tab', { name: /^字幕/ }));+ for (const { value: language } of appLanguageOptions) {+ fireEvent.click(screen.getByRole('button', { name: language }));+ const l = createLocalizedCopy(language);+ expect(within(workspace).getByRole('button', { name: l('译文 SRT', 'Translated SRT') })).toBeVisible();+ expect(within(workspace).getByRole('button', { name: l('双语 SRT', 'Bilingual SRT') })).toBeVisible();+ expect(within(workspace).getByRole('button', { name: l('保存字幕', 'Save subtitles') })).toBeEnabled();+ expect(within(workspace).getByRole('textbox', { name: `${l('字幕', 'Subtitles')} 1` })).toHaveValue('你好世界');+ expect(within(workspace).getByRole('textbox', { name: l(`${l('字幕', 'Subtitles')}原文 1`, `${l('字幕', 'Subtitles')} source 1`) })).toHaveValue('Hello');+ }+ });it.each([['running', 'queued', '翻译任务等待执行'],['running', 'running', '翻译进行中'],@@ -597,15 +773,21 @@ describe('VideoTranslationWorkspace task controls', () => {view = render(<LanguageProvider initialPreference="zh-CN"><CreatorSessionProvider- initialJob={job({ status: 'draft', revision: 0, stages: [], state: { currentStep: 0, furthestStep: 0 } })}+ initialJob={job({ status: 'draft', revision: 0, stages: [], state: { sourceUrl: '', currentStep: 0, furthestStep: 0 } })}service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}><VideoTranslationWorkspace onBack={vi.fn()} /></CreatorSessionProvider></LanguageProvider>);+ const videoTab = screen.getByRole('tab', { name: '翻译视频' });+ expect(videoTab).toHaveAttribute('aria-selected', 'true');+ expect(screen.getByRole('button', { name: '选择本地视频' })).toBeVisible();+ expect(screen.getByRole('textbox', { name: '视频链接' })).toBeVisible();const file = new File(['video'], 'portrait.mp4', { type: 'video/mp4' });fireEvent.change(screen.getByLabelText('上传本地视频'), { target: { files: [file] } });+ expect(videoTab).toHaveAttribute('aria-selected', 'true');+ fireEvent.click(videoTab);const sourceVideo = screen.getByLabelText('本地视频预览');Object.defineProperties(sourceVideo, {videoWidth: { configurable: true, value: 1080 },diff --git a/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx b/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsxindex 55eb8e74..159a8d75 100644--- a/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx+++ b/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx@@ -14,6 +14,7 @@ import {ArrowRight,Check,ChevronDown,+ Captions,FileVideo,History,Languages,@@ -65,7 +66,7 @@ import {type VideoMetadataResponse} from '@opencreator/protocol';-type SourceType = 'url' | 'file';+type SourceType = 'url' | 'file' | 'subtitle';type SubtitlePosition = 'top' | 'bottom';type SubtitleFont = 'system' | 'sans' | 'serif' | 'rounded';type SubtitleWeight = 'regular' | 'medium' | 'bold';@@ -127,6 +128,8 @@ type SubtitleStyleSettings = Pick<type TranslationSourceSnapshot = {sourceType: SourceType;+ subtitleArtifactId?: string;+ subtitleFileName?: string;videoUrl: string;videoFile: File | null;videoFileName: string | null;@@ -157,7 +160,7 @@ type LanguageOption = {label: string;};-const steps = ['添加视频', '翻译设置', '视频与字幕'] as const;+const videoSteps = ['添加素材', '翻译设置', '视频与字幕'] as const;let componentNavigationDraft: { jobId: string | null; settings: TranslationSettingsSnapshot; source: TranslationSourceSnapshot; currentStep: WizardStep; furthestStep: WizardStep; workspacePhase: WorkspacePhase } | undefined;const subtitleColors = ['#FFFFFF', '#FFE45C', '#7EE7FF', '#A7F3D0', '#000000'] as const;const defaultSubtitleStyle: SubtitleStyleSettings = {@@ -353,6 +356,7 @@ function localSourceFingerprint(source: TranslationSourceSnapshot) {function sameSource(left: TranslationSourceSnapshot, right: TranslationSourceSnapshot) {if (left.sourceType !== right.sourceType) return false;+ if (left.sourceType === 'subtitle') return left.subtitleArtifactId === right.subtitleArtifactId;if (left.sourceType === 'url') return left.videoUrl === right.videoUrl;const leftFile = localSourceFingerprint(left);const rightFile = localSourceFingerprint(right);@@ -493,6 +497,8 @@ function serializeResultVersions(versions: TranslationResultVersion[]): CreatorJ...version,source: {sourceType: version.source.sourceType,+ ...(version.source.subtitleArtifactId ? { subtitleArtifactId: version.source.subtitleArtifactId } : {}),+ ...(version.source.subtitleFileName ? { subtitleFileName: version.source.subtitleFileName } : {}),videoUrl: version.source.videoUrl,videoFileName: version.source.videoFile?.name ?? version.source.videoFileName,videoFileSize: version.source.videoFile?.size ?? version.source.videoFileSize,@@ -520,7 +526,7 @@ function deserializeResultVersions(value: CreatorJson | undefined): TranslationR) return [];const sourceRecord = source as Record<string, CreatorJson>;const settingsRecord = settings as Record<string, CreatorJson>;- if (sourceRecord.sourceType !== 'url' && sourceRecord.sourceType !== 'file') return [];+ if (sourceRecord.sourceType !== 'url' && sourceRecord.sourceType !== 'file' && sourceRecord.sourceType !== 'subtitle') return [];if (typeof sourceRecord.videoUrl !== 'string') return [];if (typeof settingsRecord.sourceLanguage !== 'string'@@ -551,6 +557,8 @@ function deserializeResultVersions(value: CreatorJson | undefined): TranslationRdescription: version.description,source: {sourceType: sourceRecord.sourceType,+ ...(typeof sourceRecord.subtitleArtifactId === 'string' ? { subtitleArtifactId: sourceRecord.subtitleArtifactId } : {}),+ ...(typeof sourceRecord.subtitleFileName === 'string' ? { subtitleFileName: sourceRecord.subtitleFileName } : {}),videoUrl: sourceRecord.videoUrl,videoFile: null,videoFileName: typeof sourceRecord.videoFileName === 'string'@@ -787,8 +795,8 @@ function legacyResultVersionsFromArtifacts(? settings as Record<string, CreatorJson>: fallbackState;const persisted = persistedVersions.find(version => version.value === value);- const resultSourceType = sourceState.sourceType === 'file'- ? 'file'+ const resultSourceType = sourceState.sourceType === 'file' || sourceState.sourceType === 'subtitle'+ ? sourceState.sourceType: persisted?.source.sourceType ?? 'url';const hasHorizontal = group.some(artifact => artifact.kind === 'horizontal_video');const hasVertical = group.some(artifact => artifact.kind === 'vertical_video');@@ -811,6 +819,8 @@ function legacyResultVersionsFromArtifacts(: `字幕版本 V${value}`,source: {sourceType: resultSourceType,+ subtitleArtifactId: sourceState.importedSourceSubtitleId ?? persisted?.source.subtitleArtifactId ?? null,+ subtitleFileName: artifactFileName(artifacts.find(artifact => artifact.id === sourceState.importedSourceSubtitleId)) ?? persisted?.source.subtitleFileName ?? null,videoUrl: typeof sourceState.sourceUrl === 'string'? sourceState.sourceUrl: persisted?.source.videoUrl ?? '',@@ -903,9 +913,9 @@ function resultVersionFromSnapshot(if (subtitleArtifact === undefined && videoArtifacts.length === 0) return undefined;const persisted = persistedVersions.find(version => version.value === snapshot.version);const sourceState = snapshot.state;- const resultSourceType = sourceState.sourceType === 'file'- ? 'file'- : persisted?.source.sourceType ?? (fallbackState.sourceType === 'file' ? 'file' : 'url');+ const resultSourceType = sourceState.sourceType === 'file' || sourceState.sourceType === 'subtitle'+ ? sourceState.sourceType+ : persisted?.source.sourceType ?? (fallbackState.sourceType === 'file' || fallbackState.sourceType === 'subtitle' ? fallbackState.sourceType : 'url');const hasHorizontal = (artifactRefs.horizontal_video?.length ?? 0) > 0;const hasVertical = (artifactRefs.vertical_video?.length ?? 0) > 0;const inferredVideoFormat = hasHorizontal && hasVertical@@ -923,6 +933,8 @@ function resultVersionFromSnapshot(description: snapshot.description || `项目版本 V${snapshot.version}`,source: {sourceType: resultSourceType,+ subtitleArtifactId: sourceState.importedSourceSubtitleId ?? persisted?.source.subtitleArtifactId ?? null,+ subtitleFileName: artifactFileName(artifacts.find(artifact => artifact.id === sourceState.importedSourceSubtitleId)) ?? persisted?.source.subtitleFileName ?? null,videoUrl: typeof sourceState.sourceUrl === 'string'? sourceState.sourceUrl: persisted?.source.videoUrl ?? (typeof fallbackState.sourceUrl === 'string' ? fallbackState.sourceUrl : ''),@@ -1630,6 +1642,8 @@ export default function VideoTranslationWorkspace(props: {const [furthestStep, setFurthestStep] = useState<WizardStep>(0);const [workspacePhase, setWorkspacePhase] = useState<WorkspacePhase>('configure');const [sourceType, setSourceType] = useState<SourceType>('url');+ const subtitleOnly = sourceType === 'subtitle';+ const steps = subtitleOnly ? videoSteps.slice(0, 2) : videoSteps;const [videoUrl, setVideoUrl] = useState('');const [videoFile, setVideoFile] = useState<File | null>(null);const [sourceDimensions, setSourceDimensions] = useState<{ width: number; height: number }>();@@ -1664,7 +1678,8 @@ export default function VideoTranslationWorkspace(props: {const [ttsModel, setTtsModel] = useState('gpt-4o-mini-tts');const [voiceCode, setVoiceCode] = useState('');const [voiceName, setVoiceName] = useState('');- const [composeVideo, setComposeVideo] = useState(false);+ const [composeVideoRequested, setComposeVideo] = useState(false);+ const composeVideo = !subtitleOnly && composeVideoRequested;const dubbing = composeVideo && dubbingRequested;const [videoFormat, setVideoFormat] = useState<VideoFormat>('horizontal');const [sourceOrientation, setSourceOrientation] = useState<VideoOrientation>(() => (@@ -1682,6 +1697,7 @@ export default function VideoTranslationWorkspace(props: {const [resultNotice, setResultNotice] = useState('');const [voicePreviewReload, setVoicePreviewReload] = useState(0);const [submitting, setSubmitting] = useState(false);+ const [subtitleImportPending, setSubtitleImportPending] = useState(false);const [submissionPhase, setSubmissionPhase] = useState<'uploading' | 'starting'>();const [startRevisionConflict, setStartRevisionConflict] = useState(false);const [taskControlPending, setTaskControlPending] = useState<'canceling' | 'resuming'>();@@ -1735,7 +1751,7 @@ export default function VideoTranslationWorkspace(props: {if (creatorSession === null) return;skipPersistRef.current = true;const persisted = creatorSession.state;- if (persisted.sourceType === 'url' || persisted.sourceType === 'file') setSourceType(persisted.sourceType);+ if (persisted.sourceType === 'url' || persisted.sourceType === 'file' || persisted.sourceType === 'subtitle') setSourceType(persisted.sourceType);if (typeof persisted.sourceUrl === 'string') setVideoUrl(persisted.sourceUrl);setVideoFileName(typeof persisted.sourceFileName === 'string' ? persisted.sourceFileName : null);setVideoFileSize(typeof persisted.sourceFileSize === 'number' ? persisted.sourceFileSize : null);@@ -1799,10 +1815,10 @@ export default function VideoTranslationWorkspace(props: {if (typeof persisted.verticalTitle === 'string') setVerticalTitle(persisted.verticalTitle);if (typeof persisted.verticalSubtitle === 'string') setVerticalSubtitle(persisted.verticalSubtitle);if (persisted.currentStep === 0 || persisted.currentStep === 1 || persisted.currentStep === 2 || persisted.currentStep === 3) {- setCurrentStep(persisted.currentStep === 3 ? 2 : persisted.currentStep);+ setCurrentStep(Math.min(persisted.currentStep, persisted.sourceType === 'subtitle' ? 1 : 2) as WizardStep);}if (persisted.furthestStep === 0 || persisted.furthestStep === 1 || persisted.furthestStep === 2 || persisted.furthestStep === 3) {- setFurthestStep(persisted.furthestStep === 3 ? 2 : persisted.furthestStep);+ setFurthestStep(Math.min(persisted.furthestStep, persisted.sourceType === 'subtitle' ? 1 : 2) as WizardStep);}const artifactVersions = resultVersionsFromArtifacts(creatorSession.job.artifacts, persisted);const latest = artifactVersions.at(-1);@@ -1826,13 +1842,14 @@ export default function VideoTranslationWorkspace(props: {}if (latest !== undefined) {if (!shouldRestoreLatestResult) return;- setCurrentStep(2);- setFurthestStep(2);+ setCurrentStep(persisted.sourceType === 'subtitle' ? 1 : 2);+ setFurthestStep(persisted.sourceType === 'subtitle' ? 1 : 2);setResultVersion(persistedVersion?.value ?? latest.value);setDraftBaseVersion(latest.value);- setResultTab('video');+ setResultTab(latest.source.sourceType === 'subtitle' ? 'subtitles' : 'video');setWorkspacePhase('result');} else if (shouldRestoreLatestResult) {+ if (persisted.sourceType === 'subtitle') setResultTab('subtitles');setDraftBaseVersion(undefined);setWorkspacePhase(creatorSession.job.status !== 'draft'&& creatorSession.job.stages.some(stage => ['subtitle', 'tts', 'render-horizontal', 'render-vertical'].includes(stage.stageId))@@ -2151,7 +2168,9 @@ export default function VideoTranslationWorkspace(props: {const selectedFileRegistered = videoFile !== null&& registeredSourceArtifact !== undefined&& sourceArtifactMatchesFile(registeredSourceArtifact, videoFile);- const hasSource = sourceType === 'url'+ const importedSourceSubtitle = creatorSession?.job.artifacts.find(artifact => artifact.id === creatorSession.state.importedSourceSubtitleId+ && artifact.kind === 'source_subtitle' && artifact.status === 'completed');+ const hasSource = subtitleOnly ? importedSourceSubtitle !== undefined : sourceType === 'url'? isValidVideoUrl(videoUrl): videoFile !== null || videoFileName !== null || registeredSourceArtifact !== undefined;const latestStage = creatorSession?.job.stages.at(-1);@@ -2210,7 +2229,7 @@ export default function VideoTranslationWorkspace(props: {translationStartedNotice,startRevisionConflict]);- const sourceName = sourceType === 'url'+ const sourceName = subtitleOnly ? artifactFileName(importedSourceSubtitle) ?? l('等待上传字幕', 'Waiting for subtitles') : sourceType === 'url'? (videoUrl.trim() || l('等待填写链接', 'Waiting for a link')): (videoFile?.name?? videoFileName@@ -2227,6 +2246,7 @@ export default function VideoTranslationWorkspace(props: {], [bilingual, composeVideo, dubbing, l, outputLabel, sourceLanguage, subtitlePosition, subtitleStyleLabel, targetLanguage, voiceCode, voiceName]);const targetLanguageLabel = languageLabel(targetLanguages, targetLanguage);const selectedResult = resultVersions.find(version => version.value === resultVersion);+ const selectedSubtitleOnly = (selectedResult?.source.sourceType ?? sourceType) === 'subtitle';const generationStage = [...(creatorSession?.job.stages ?? [])].reverse().find(stage => (['subtitle', 'tts', 'render-horizontal', 'render-vertical'].includes(stage.stageId)));@@ -2413,7 +2433,7 @@ export default function VideoTranslationWorkspace(props: {const baseHorizontalSubtitleCues = subtitleCuesWithSource(selectedSubtitleCues,selectedSourceSubtitleArtifact,- selectedResultSettings?.bilingual === true+ selectedSubtitleOnly || selectedResultSettings?.bilingual === true);const baseVerticalSubtitleCues = subtitleCuesFromArtifact(selectedVerticalSubtitleArtifact);const displayedHorizontalSubtitleCues = applySubtitleTextEdits(@@ -2496,7 +2516,8 @@ export default function VideoTranslationWorkspace(props: {const selectedSubtitleStyleLabel = selectedResultSettings? `${subtitleFontLabel(selectedResultSettings.subtitleFont, l)} · ${subtitleWeightLabel(selectedResultSettings.subtitleWeight, l)} · ${subtitleSizeLabel(selectedResultSettings.subtitleSize, l)} · ${selectedResultSettings.subtitleColor.toUpperCase()}`: subtitleStyleLabel;- const selectedSourceName = selectedResultSource === undefined ? sourceName : selectedResultSource.sourceType === 'url'+ const selectedSourceName = selectedResultSource === undefined ? sourceName : selectedResultSource.sourceType === 'subtitle'+ ? selectedResultSource.subtitleFileName ?? sourceName : selectedResultSource.sourceType === 'url'? (selectedResultSource.videoUrl.trim() || l('等待填写链接', 'Waiting for a link')): (selectedResultSource?.videoFile?.name?? selectedResultSource?.videoFileName@@ -2506,11 +2527,11 @@ export default function VideoTranslationWorkspace(props: {vertical: subtitleTextChanged(baseVerticalSubtitleCues, displayedVerticalSubtitleCues)};const subtitleDirty = subtitleDirtyByVariant.horizontal === true;- const subtitleNeedsRegeneration = selectedResult+ const subtitleNeedsRegeneration = !selectedSubtitleOnly && selectedResult? JSON.stringify(stripSubtitleSourceText(displayedHorizontalSubtitleCues))!== selectedResult.generatedSubtitleSnapshot: false;- const selectedHasStaleArtifacts = (selectedResult?.staleArtifactIds.length ?? 0) > 0;+ const selectedHasStaleArtifacts = !selectedSubtitleOnly && (selectedResult?.staleArtifactIds.length ?? 0) > 0;const staleArtifactKinds = new Set((selectedResult?.staleArtifactIds ?? []).flatMap(id => {const artifact = jobArtifacts.find(candidate => candidate.id === id);@@ -2551,6 +2572,7 @@ export default function VideoTranslationWorkspace(props: {setAttemptedContinue(true);return;}+ step = Math.min(step, steps.length - 1) as WizardStep;setCurrentStep(step);setFurthestStep(previous => Math.max(previous, step) as WizardStep);}@@ -2590,6 +2612,7 @@ export default function VideoTranslationWorkspace(props: {function currentDraftSource(): TranslationSourceSnapshot {return {sourceType,+ ...(subtitleOnly && importedSourceSubtitle ? { subtitleArtifactId: importedSourceSubtitle.id, subtitleFileName: artifactFileName(importedSourceSubtitle) } : {}),videoUrl,videoFile,videoFileName,@@ -2630,6 +2653,9 @@ export default function VideoTranslationWorkspace(props: {function applySourceSnapshot(source: TranslationSourceSnapshot) {setSourceType(source.sourceType);+ if (source.sourceType === 'subtitle' && source.subtitleArtifactId) {+ creatorSession?.updateDraft({ importedSourceSubtitleId: source.subtitleArtifactId, importedTargetSubtitleId: null });+ }setVideoUrl(source.videoUrl);setVideoFile(source.videoFile);setVideoFileName(source.videoFile?.name ?? source.videoFileName);@@ -2684,8 +2710,14 @@ export default function VideoTranslationWorkspace(props: {}const draftAppliesToSelectedResult = selectedResult !== undefined&& draftBaseVersion === selectedResult.value;+ const settingsMatchSelectedResult = selectedResult === undefined || (selectedSubtitleOnly+ ? draftSettingsSnapshot.sourceLanguage === selectedResult.settings.sourceLanguage+ && draftSettingsSnapshot.targetLanguage === selectedResult.settings.targetLanguage+ && draftSettingsSnapshot.bilingual === selectedResult.settings.bilingual+ && draftSettingsSnapshot.subtitlePosition === selectedResult.settings.subtitlePosition+ : sameSettings(draftSettingsSnapshot, selectedResult.settings));const hasConfigDraftChanges = draftAppliesToSelectedResult- && (!sameSettings(draftSettingsSnapshot, selectedResult.settings)+ && (!settingsMatchSelectedResult|| !sameSource(draftSourceSnapshot, selectedResult.source));const hasPendingChanges = subtitleNeedsRegeneration|| hasConfigDraftChanges@@ -2879,6 +2911,7 @@ export default function VideoTranslationWorkspace(props: {}async function submit() {+ if (subtitleImportPending) return;if (!hasSource || !sourceSelectionReady) {setCurrentStep(0);setAttemptedContinue(true);@@ -2930,6 +2963,7 @@ export default function VideoTranslationWorkspace(props: {});}setWorkspacePhase('result');+ if (subtitleOnly) setResultTab('subtitles');setDraftBaseVersion(undefined);setResultNotice(isRegeneration? stageId === undefined@@ -3073,8 +3107,10 @@ export default function VideoTranslationWorkspace(props: {setSubmitting(true);try {const saved = await persistSubtitleVariant(variant, selectedResult.value);- const variantLabel = variant === 'horizontal' ? '横屏' : '竖屏';- setResultNotice(saved.hasStaleArtifacts+ const variantLabel = selectedSubtitleOnly ? '' : variant === 'horizontal' ? '横屏' : '竖屏';+ setResultNotice(selectedSubtitleOnly+ ? l(`字幕已保存,项目仍为 V${saved.version}`, `Subtitles were saved; the project remains V${saved.version}.`)+ : saved.hasStaleArtifacts? l(`${variantLabel}字幕已保存,项目仍为 V${saved.version}。现有配音或成片已保留,重新生成后会更新`,`${variant === 'horizontal' ? 'Horizontal' : 'Vertical'} subtitles were saved; the project remains V${saved.version}. Existing dubbing or videos are preserved until regenerated.`@@ -3136,7 +3172,7 @@ export default function VideoTranslationWorkspace(props: {setDraftBaseVersion(selectedResult.value);setWorkspacePhase('configure');setCurrentStep(1);- setFurthestStep(2);+ setFurthestStep(selectedSubtitleOnly ? 1 : 2);setResultProposal(undefined);setResultNotice('');}@@ -3145,7 +3181,7 @@ export default function VideoTranslationWorkspace(props: {const version = draftBaseVersion ?? resultVersion;setResultVersion(version);setWorkspacePhase('result');- setResultTab('video');+ setResultTab(selectedSubtitleOnly ? 'subtitles' : 'video');setResultProposal(undefined);setResultNotice(l(`已返回 V${version},配置草稿仍然保留`, `Returned to V${version}. Your configuration draft is still saved.`));}@@ -3214,16 +3250,16 @@ export default function VideoTranslationWorkspace(props: {<Languages size={20} strokeWidth={1.8} /></span><div className="video-translation-header-copy">- <h1>{workspacePhase === 'result' ? l('视频翻译项目', 'Video Translation Project') : l('视频翻译配音', 'Translate & Dub Video')}</h1>- <p>{workspacePhase === 'result' ? selectedSourceName : l('创建字幕、配音与多画幅成片', 'Create subtitles, dubbing, and videos in multiple formats')}</p>+ <h1>{(workspacePhase === 'result' ? selectedSubtitleOnly : subtitleOnly) ? l('字幕翻译', 'Subtitle Translation') : workspacePhase === 'result' ? l('视频翻译项目', 'Video Translation Project') : l('视频翻译配音', 'Translate & Dub Video')}</h1>+ <p>{workspacePhase === 'result' ? selectedSourceName : subtitleOnly ? sourceName : l('创建字幕、配音与多画幅成片', 'Create subtitles, dubbing, and videos in multiple formats')}</p></div></header>{workspacePhase === 'configure' ? (<div className="video-translation-configure-top">- <LocalTranscriptionNotice controller={props.runtimeDependencies}+ {!subtitleOnly ? <LocalTranscriptionNotice controller={props.runtimeDependencies}importedSubtitle={typeof creatorSession?.state.importedSourceSubtitleId === 'string' || typeof creatorSession?.state.importedTargetSubtitleId === 'string'}- beforeNavigate={preserveComponentNavigationDraft} />+ beforeNavigate={preserveComponentNavigationDraft} /> : null}{draftBaseVersion !== undefined ? (<div className="video-translation-draft-bar" role="status"><History size={16} strokeWidth={1.8} aria-hidden="true" />@@ -3264,7 +3300,8 @@ export default function VideoTranslationWorkspace(props: {<div className="video-translation-wizard-body" key={`${workspacePhase}-${currentStep}`}>{workspacePhase === 'result' ? (<VideoTranslationResultWorkspace- activeTab={resultTab}+ subtitleOnly={selectedSubtitleOnly}+ activeTab={selectedSubtitleOnly && (resultTab === 'video' || resultTab === 'voice') ? 'subtitles' : resultTab}version={resultVersion}versions={resultVersions.map(({ value, description }) => ({ value, description }))}targetLanguage={selectedTargetLanguageLabel}@@ -3273,7 +3310,14 @@ export default function VideoTranslationWorkspace(props: {dubbing={selectedResultSettings?.dubbing ?? (composeVideo && dubbing)}hasVoiceArtifact={hasVoiceArtifact}videoOutputs={videoOutputs}- subtitleOutputs={subtitleOutputs}+ subtitleOutputs={selectedSubtitleOnly ? subtitleOutputs.filter(output => output.variant === 'horizontal') : subtitleOutputs}+ subtitleDownloads={selectedSubtitleOnly ? [+ { kind: 'target_subtitle', label: l('译文 SRT', 'Translated SRT') },+ { kind: 'bilingual_subtitle', label: l('双语 SRT', 'Bilingual SRT') }+ ].flatMap(({ kind, label }) => {+ const artifact = latestArtifactForResultVersion(jobArtifacts, resultVersion, [kind], creatorSession?.state.resultSnapshots);+ return artifact ? [{ artifactId: artifact.id, label }] : [];+ }) : undefined}subtitleVideoPreviews={subtitleVideoPreviews}previewPreparation={{ pending: Boolean(sourcePreviewPending), blocked: activeStage !== undefined, error: sourcePreviewError, errorDetail: sourcePreviewErrorDetail }}onPrepareSourceVideo={canPrepareSourcePreview ? () => void prepareSourcePreview() : undefined}@@ -3308,7 +3352,28 @@ export default function VideoTranslationWorkspace(props: {{workspacePhase === 'configure' && currentStep === 0 ? (<>- <VideoSourceInput+ <div className="video-translation-source-modes" role="tablist" aria-label={l('素材类型', 'Source type')}>+ {([+ { value: 'url', label: l('翻译视频', 'Translate video'), icon: FileVideo },+ { value: 'subtitle', label: l('翻译字幕', 'Translate subtitles'), icon: Captions }+ ] as const).map(({ value, label, icon: Icon }) => <button+ key={value} type="button" role="tab" aria-selected={value === 'subtitle' ? subtitleOnly : !subtitleOnly}+ disabled={submitting || subtitleImportPending || activeStage !== undefined}+ onClick={() => {+ if ((value === 'subtitle') === subtitleOnly) return;+ setSourceType(value);+ setAttemptedContinue(false);+ setCurrentStep(0);+ setFurthestStep(0);+ creatorSession?.updateDraft({ sourceType: value,+ ...(subtitleOnly && value !== 'subtitle' ? { importedSourceSubtitleId: null, importedTargetSubtitleId: null } : {}) });+ }}+ ><Icon size={16} aria-hidden="true" />{label}</button>)}+ </div>+ {subtitleOnly ? <section className="video-translation-step-panel video-translation-subtitle-source-step">+ <div className="video-translation-step-heading"><h2>{l('添加字幕', 'Add subtitles')}</h2></div>+ <VideoTranslationSubtitleImport sourceOnly sourceLanguage={sourceLanguage} targetLanguage={targetLanguage} disabled={submitting || activeStage !== undefined} onBusyChange={setSubtitleImportPending} />+ </section> : <VideoSourceInputshowSupportedPlatformsfile={videoFile}registeredFile={registeredSourceFile}@@ -3340,7 +3405,7 @@ export default function VideoTranslationWorkspace(props: {onMetadata={(url, metadata) => {setUrlMetadata({ url, value: metadata });}}- />+ />}{sourceType === 'url' && parsedVideoSource.kind === 'bilibili' ? (<BilibiliPartSelectormetadata={currentUrlMetadata}@@ -3360,7 +3425,7 @@ export default function VideoTranslationWorkspace(props: {<section className="video-translation-step-panel" aria-labelledby="translation-settings-title"><div className="video-translation-step-heading"><h2 id="translation-settings-title">{l('设置翻译语言', 'Set translation languages')}</h2>- <p>{l('选择视频原语言、目标语言和字幕内容方式', 'Choose the source language, target language, and subtitle content')}</p>+ {!subtitleOnly ? <p>{l('选择视频原语言、目标语言和字幕内容方式', 'Choose the source language, target language, and subtitle content')}</p> : null}</div><div className="video-translation-language-row">@@ -3388,7 +3453,7 @@ export default function VideoTranslationWorkspace(props: {</div><div className="video-translation-toggle-list" data-agent-focus={agentFocus === 'subtitles'}>- <VideoTranslationSubtitleImport sourceLanguage={sourceLanguage} targetLanguage={targetLanguage} disabled={submitting || activeStage !== undefined} />+ {!subtitleOnly ? <VideoTranslationSubtitleImport sourceLanguage={sourceLanguage} targetLanguage={targetLanguage} disabled={submitting || activeStage !== undefined} /> : null}<Switchchecked={bilingual}label={l('双语字幕', 'Bilingual subtitles')}@@ -3406,13 +3471,13 @@ export default function VideoTranslationWorkspace(props: {</div></div>) : null}- <Switch+ {!subtitleOnly ? <Switchchecked={preferPlatformCaptions && sourceType === 'url'}label={l('优先使用平台字幕', 'Prefer platform subtitles')}description={sourceType === 'url' ? l('平台无字幕时自动识别', 'Transcribe automatically when platform subtitles are unavailable') : l('仅视频链接可用', 'Available for video links only')}disabled={sourceType !== 'url'}onChange={setPreferPlatformCaptions}- />+ /> : null}</div></section>) : null}@@ -3763,17 +3828,17 @@ export default function VideoTranslationWorkspace(props: {) : currentStep === 0 ? (<div className="video-translation-action-group">{attemptedContinue && !hasSource ? (- <p className="video-translation-error" role="alert">{l('请先添加需要翻译的视频', 'Add a video to translate first')}</p>+ <p className="video-translation-error" role="alert">{subtitleOnly ? l('请先添加需要翻译的 SRT 字幕', 'Add an SRT file to translate first') : l('请先添加需要翻译的视频', 'Add a video to translate first')}</p>) : null}{attemptedContinue && hasSource && !sourceSelectionReady ? (<p className="video-translation-error" role="alert">{l('请确认链接有效,并选择要翻译的分集后继续', 'Check the link and choose a part before continuing')}</p>) : null}- <button className="video-translation-primary-action" type="button" onClick={continueToSettings}>+ <button className="video-translation-primary-action" type="button" disabled={subtitleImportPending} onClick={continueToSettings}>{l('继续', 'Continue')}<ArrowRight size={16} strokeWidth={1.8} aria-hidden="true" /></button></div>- ) : currentStep < 2 ? (+ ) : currentStep < steps.length - 1 ? (<button className="video-translation-primary-action" type="button" onClick={() => openWizardStep((currentStep + 1) as WizardStep)}>{l('继续', 'Continue')}<ArrowRight size={16} strokeWidth={1.8} aria-hidden="true" />@@ -3807,8 +3872,8 @@ export default function VideoTranslationWorkspace(props: {stepLabel={workspacePhase === 'result' ? l('项目结果', 'Project results') : localizeStep(steps[currentStep], l)}contextSummary={agentContextSummary}taskSummary={<CreatorTaskSummary- sourceIcon={FileVideo}- sourceLabel={l('视频来源', 'Video source')}+ sourceIcon={subtitleOnly ? Captions : FileVideo}+ sourceLabel={subtitleOnly ? l('字幕文件', 'Subtitle file') : l('视频来源', 'Video source')}sourceValue={sourceName}items={summaryItems}compactSummary={`${languageLabel(sourceLanguages, sourceLanguage)} → ${targetLanguageLabel} · ${outputLabel}`}@@ -4092,10 +4157,10 @@ function creatorServicesSettingsHref(...codes: Array<string | null | undefined>)return `#/settings?tab=ai-services§ion=${section}`;}-function localizeStep(step: typeof steps[number], l: LocalizeCopy): string {- if (step === '添加视频') return l(step, 'Add video');+function localizeStep(step: typeof videoSteps[number] | undefined, l: LocalizeCopy): string {+ if (step === '添加素材') return l(step, 'Add source');if (step === '翻译设置') return l(step, 'Translation');- return l(step, 'Video & subtitles');+ return l(step ?? '翻译设置', 'Video & subtitles');}function localizeFormatLabel(label: '横屏' | '竖屏' | '全部', l: LocalizeCopy): string {diff --git a/apps/web/src/features/dashboard/creator-preflight-copy.test.ts b/apps/web/src/features/dashboard/creator-preflight-copy.test.tsindex b228235e..d3afbce3 100644--- a/apps/web/src/features/dashboard/creator-preflight-copy.test.ts+++ b/apps/web/src/features/dashboard/creator-preflight-copy.test.ts@@ -3,7 +3,7 @@ import { createLocalizedCopy } from '../../i18n/localized-copy.js';import { creatorPreflightMessage } from './creator-preflight-copy.js';describe('localized preflight guidance', () => {- it.each(['input-result-version', 'bilibili-part', 'image-provider', 'transcription-capability', 'transcription-config', 'input-file', 'executor', 'yt-dlp', 'krillin-runtime', 'unknown-executor'])('supports all display languages for %s', id => {+ it.each(['input-subtitle', 'input-result-version', 'bilibili-part', 'image-provider', 'transcription-capability', 'transcription-config', 'input-file', 'executor', 'yt-dlp', 'krillin-runtime', 'unknown-executor'])('supports all display languages for %s', id => {const chinese = creatorPreflightMessage(id, createLocalizedCopy('zh-CN'));const english = creatorPreflightMessage(id, createLocalizedCopy('en-US'));const swedish = creatorPreflightMessage(id, createLocalizedCopy('sv-SE'));diff --git a/apps/web/src/features/dashboard/creator-preflight-copy.ts b/apps/web/src/features/dashboard/creator-preflight-copy.tsindex ea5e19ae..87ec26e8 100644--- a/apps/web/src/features/dashboard/creator-preflight-copy.ts+++ b/apps/web/src/features/dashboard/creator-preflight-copy.ts@@ -1,6 +1,7 @@import type { LocalizeCopy } from '../../i18n/localized-copy.js';const messages: Record<string, [string, string, string]> = {+ 'input-subtitle': ['请先添加需要翻译的 SRT 字幕', 'Add an SRT file to translate first', 'Lägg till en SRT-fil att översätta först'],'input-result-version': ['请先选择有效的已保存项目版本,再准备预览视频。', 'Select a valid saved result version before preparing preview media.', 'Välj en giltig sparad resultatversion innan du förbereder förhandsvisningsvideon.'],'bilibili-part': ['请检查 B 站链接,并确认要翻译的视频分集后重试。', 'Check the Bilibili URL and confirm the video part before retrying.', 'Kontrollera Bilibili-länken och bekräfta videodelen innan du försöker igen.'],'image-provider': ['图像生成尚未就绪,请检查登录、服务配置及 Runtime 工具支持。', 'Image generation is not ready. Check sign-in, service configuration, and Runtime tool support.', 'Bildgenerering är inte redo. Kontrollera inloggningen, tjänsteinställningarna och verktygsstödet i Runtime.'],diff --git a/apps/web/src/features/dashboard/dashboard.css b/apps/web/src/features/dashboard/dashboard.cssindex 98f3ae96..38ba2818 100644--- a/apps/web/src/features/dashboard/dashboard.css+++ b/apps/web/src/features/dashboard/dashboard.css@@ -899,6 +899,16 @@outline-offset: 2px;}+.video-translation-subtitle-file-picker .video-translation-subtitle-remove {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 28px;+ height: 28px;+ margin-left: auto;+ padding: 0;+}+.video-translation-subtitle-file-picker > span {min-width: 0;overflow: hidden;@@ -14707,6 +14717,78 @@gap: 18px;}+.video-result-subtitle-preview-layout[data-subtitle-only="true"] {+ grid-template-columns: minmax(0, 1fr);+}++.video-translation-source-modes {+ display: flex;+ flex-wrap: wrap;+ gap: 4px;+ border-bottom: 1px solid var(--border);+ margin-bottom: 20px;+}++.video-translation-source-modes button {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 6px;+ min-height: 40px;+ padding: 8px 12px;+ color: inherit;+ background: transparent;+ border: 0;+ border-bottom: 2px solid transparent;+ cursor: pointer;+}++.video-translation-source-modes button[aria-selected="true"] {+ color: var(--accent);+ border-bottom-color: currentColor;+}++.video-translation-subtitle-source-step {+ width: min(800px, 100%);+ min-width: 0;+ margin: 0 auto;+ box-sizing: border-box;+ border: 0;+ background: transparent;+}++.video-translation-wizard-main[data-phase="configure"] .video-translation-subtitle-source-step {+ padding-block: 8px;+}++.video-translation-wizard-main[data-phase="configure"] .video-translation-subtitle-source-step .video-translation-step-heading {+ margin-bottom: 12px;+}++.video-translation-subtitle-source-step .video-translation-step-heading h2 {+ font-size: 14px;+ font-weight: 600;+}++.video-translation-subtitle-source-step fieldset {+ min-inline-size: 0;+}++.video-translation-subtitle-source-step details {+ overflow-wrap: anywhere;+}++.video-translation-subtitle-source-step pre {+ max-height: 320px;+ overflow: auto;+ margin: 12px 0 0;+ color: var(--text);+ font-family: inherit;+ font-size: 13px;+ line-height: 1.6;+ white-space: pre-wrap;+}+.video-result-subtitle-pane {container-type: inline-size;container-name: video-result-subtitles;@@ -14945,6 +15027,16 @@}@container video-result-subtitles (max-width: 600px) {+ .video-result-subtitle-preview-layout[data-subtitle-only="true"] .video-subtitle-cue {+ grid-template-columns: minmax(0, 1fr);+ gap: 6px;+ }++ .video-result-subtitle-preview-layout[data-subtitle-only="true"] .video-subtitle-cue-time {+ display: flex;+ gap: 10px;+ }+.video-result-subtitle-preview-layout {grid-template-columns: minmax(0, 1fr);grid-template-rows: auto auto;diff --git a/apps/web/src/i18n/locales/de-DE.json b/apps/web/src/i18n/locales/de-DE.jsonindex 86083625..977756ae 100644--- a/apps/web/src/i18n/locales/de-DE.json+++ b/apps/web/src/i18n/locales/de-DE.json@@ -50,6 +50,7 @@"Add a video link": "Fügen Sie einen Videolink hinzu","Add a video to translate first": "Fügen Sie zuerst ein zu übersetzendes Video hinzu","Add a writing topic or instruction when no inspiration is provided.": "Fügen Sie ein Schreibthema oder eine Anweisung hinzu, wenn keine Inspiration vorhanden ist.",+ "Add an SRT file to translate first": "Fügen Sie zuerst eine SRT-Datei zum Übersetzen hinzu","Add content priorities, subject details, or layout requirements": "Fügen Sie Inhaltsprioritäten, Themendetails oder Layoutanforderungen hinzu","Add context": "Kontext hinzufügen","Add file": "Datei hinzufügen",@@ -62,6 +63,8 @@"Add one link at a time.": "Fügen Sie jeweils einen Link hinzu.","Add reference": "Referenz hinzufügen","Add reference image": "Referenzbild hinzufügen",+ "Add source": "Material hinzufügen",+ "Add subtitles": "Untertitel hinzufügen","Add to queue": "Zur Warteschlange hinzufügen","Add variables": "Variablen hinzufügen","Add video": "Video hinzufügen",@@ -223,6 +226,7 @@"Auto-clip now": "Jetzt automatisch zuschneiden","Auto-match voice": "Stimme automatisch anpassen","Automatic": "Automatisch",+ "Automatic captions": "Automatische Untertitel","Automatically render up to {{0}} standalone video clips": "Rendern Sie automatisch bis zu {{0}} eigenständige Videoclips","Available": "Verfügbar","Available credits": "Verfügbare Credits",@@ -248,6 +252,7 @@"Below": "Unten","Bilibili": "Bilibili","Bilibili video": "Bilibili-Video",+ "Bilingual SRT": "Zweisprachige SRT","Bilingual subtitles": "Zweisprachige Untertitel","Bilingual · translation {{0}}": "Zweisprachig · Übersetzung {{0}}","Billing and recharge history": "Abrechnungs- und Aufladeverlauf",@@ -1401,6 +1406,7 @@"Manage projects": "Projekte verwalten","Manage this in MCP settings": "Verwalten Sie dies in den MCP-Einstellungen","Managed installation unavailable on this platform": "Die verwaltete Installation ist auf dieser Plattform nicht verfügbar",+ "Manual subtitles": "Manuelle Untertitel","Manual update checks are coming soon": "Manuelle Update-Prüfungen folgen in Kürze","Many": "Viele","Maps / Charts": "Karten / Diagramme",@@ -1901,6 +1907,7 @@"Remove reference": "Verweis entfernen","Remove reference image": "Referenzbild entfernen","Remove sensitive information before use.": "Entfernen Sie vertrauliche Informationen vor der Verwendung.",+ "Remove subtitles": "Untertitel entfernen","Remove {{0}}": "{{0}} entfernen","Removed projects": "Entfernte Projekte","Rename": "Umbenennen",@@ -1919,6 +1926,7 @@"Rendering video clips automatically": "Videoclips automatisch rendern","Repair folder": "Ordner reparieren","Repeat": "Wiederholen",+ "Replace file": "Datei ersetzen","Replace image": "Bild ersetzen","Replace reference": "Referenz ersetzen","Replaceable variable": "Austauschbare Variable",@@ -2040,6 +2048,7 @@"Save memory suggestions": "Speichervorschläge speichern","Save network proxy": "Netzwerk-Proxy speichern","Save settings": "Einstellungen speichern",+ "Save subtitles": "Untertitel speichern","Save text source": "Textquelle speichern","Save to local draft": "Als lokalen Entwurf speichern","Save {{0}} subtitles": "Speichern Sie {{0}} Untertitel",@@ -2208,6 +2217,7 @@"Source record missing: {{0}}": "Quelldatensatz fehlt: {{0}}","Source subtitles": "Untertitel der Quelle","Source subtitles (skip transcription)": "Untertitel der Quelle (Transkription überspringen)",+ "Source type": "Materialtyp","Source video": "Quellvideo","Source video downloaded": "Quellvideo heruntergeladen","Source video preparation failed. Existing subtitles remain editable and downloadable.": "Die Vorbereitung des Quellvideos ist fehlgeschlagen. Vorhandene Untertitel können weiterhin bearbeitet und heruntergeladen werden.",@@ -2290,6 +2300,7 @@"Submitting the video generation task": "Senden der Aufgabe zur Videogenerierung","Submitting to the image provider": "Übermittlung an den Bildanbieter","Submitting to the provider": "Übermittlung an den Anbieter",+ "Subtitle Translation": "Untertitelübersetzung","Subtitle content": "Untertitelinhalt","Subtitle file": "Untertiteldatei","Subtitle files": "Untertiteldateien",@@ -2310,6 +2321,7 @@"Subtitles are pending": "Untertitel stehen noch aus","Subtitles generated using audio transcription because platform captions were unavailable": "Untertitel wurden mithilfe der Audiotranskription erstellt, da keine Plattformuntertitel verfügbar waren","Subtitles have not been generated for this version": "Für diese Version wurden keine Untertitel generiert",+ "Subtitles were saved; the project remains V{{0}}.": "Die Untertitel wurden gespeichert; das Projekt bleibt bei V{{0}}.","Subtitles, dubbing, and lip sync": "Untertitel, Synchronisation und Lippensynchronisation","Success last time": "Letztes Mal erfolgreich","Suggested structure": "Vorgeschlagene Struktur",@@ -2673,7 +2685,10 @@"Transcription model": "Transkriptionsmodell","Transcription provider": "Transkriptionsanbieter","Translate & Dub Video": "Video übersetzen und synchronisieren",+ "Translate subtitles": "Untertitel übersetzen","Translate to": "Übersetzen nach",+ "Translate video": "Video übersetzen",+ "Translated SRT": "Übersetzte SRT","Translated subtitles": "Übersetzte Untertitel","Translated subtitles (skip transcription and translation)": "Übersetzte Untertitel (Transkription und Übersetzung überspringen)","Translating subtitles": "Untertitel übersetzen",@@ -3004,6 +3019,7 @@"Waiting for earlier formats": "Warten auf frühere Formate","Waiting for first run": "Warten auf den ersten Lauf","Waiting for local capabilities": "Warten auf lokale Fähigkeiten",+ "Waiting for subtitles": "Warten auf Untertitel","Waiting for the local runtime": "Warten auf die lokale Laufzeit","Waiting for the video provider": "Warten auf den Videoanbieter","Waiting to analyze": "Ich warte auf die Analyse",diff --git a/apps/web/src/i18n/locales/es-ES.json b/apps/web/src/i18n/locales/es-ES.jsonindex 08de1662..25197ae7 100644--- a/apps/web/src/i18n/locales/es-ES.json+++ b/apps/web/src/i18n/locales/es-ES.json@@ -50,6 +50,7 @@"Add a video link": "Añadir un enlace de vídeo","Add a video to translate first": "Agrega un video para traducir primero","Add a writing topic or instruction when no inspiration is provided.": "Agregue un tema de escritura o una instrucción cuando no se proporcione inspiración.",+ "Add an SRT file to translate first": "Añade primero un archivo SRT para traducir","Add content priorities, subject details, or layout requirements": "Agregue prioridades de contenido, detalles del tema o requisitos de diseño","Add context": "Agregar contexto","Add file": "Agregar archivo",@@ -62,6 +63,8 @@"Add one link at a time.": "Agregue un enlace a la vez.","Add reference": "Agregar referencia","Add reference image": "Agregar imagen de referencia",+ "Add source": "Añadir material",+ "Add subtitles": "Añadir subtítulos","Add to queue": "Añadir a la cola","Add variables": "Agregar variables","Add video": "Añadir vídeo",@@ -223,6 +226,7 @@"Auto-clip now": "Recortar automáticamente ahora","Auto-match voice": "Voz de coincidencia automática","Automatic": "Automático",+ "Automatic captions": "Subtítulos automáticos","Automatically render up to {{0}} standalone video clips": "Procesa automáticamente hasta {{0}} videoclips independientes","Available": "Disponible","Available credits": "Créditos disponibles",@@ -248,6 +252,7 @@"Below": "Abajo","Bilibili": "Bilibili","Bilibili video": "vídeo de bilibili",+ "Bilingual SRT": "SRT bilingüe","Bilingual subtitles": "Subtítulos bilingües","Bilingual · translation {{0}}": "Traducción bilingüe {{0}}","Billing and recharge history": "Historial de facturación y recargas",@@ -1401,6 +1406,7 @@"Manage projects": "Gestionar proyectos","Manage this in MCP settings": "Administre esto en la configuración de MCP","Managed installation unavailable on this platform": "La instalación administrada no está disponible en esta plataforma",+ "Manual subtitles": "Subtítulos manuales","Manual update checks are coming soon": "Próximamente habrá comprobaciones de actualizaciones manuales","Many": "Muchos","Maps / Charts": "Mapas / Cartas",@@ -1901,6 +1907,7 @@"Remove reference": "Eliminar referencia","Remove reference image": "Eliminar imagen de referencia","Remove sensitive information before use.": "Elimine la información confidencial antes de su uso.",+ "Remove subtitles": "Quitar subtítulos","Remove {{0}}": "Eliminar {{0}}","Removed projects": "Proyectos eliminados","Rename": "Rebautizar",@@ -1919,6 +1926,7 @@"Rendering video clips automatically": "Renderizar videoclips automáticamente","Repair folder": "Carpeta de reparación","Repeat": "Repetir",+ "Replace file": "Cambiar archivo","Replace image": "Reemplazar imagen","Replace reference": "Reemplazar referencia","Replaceable variable": "variable reemplazable",@@ -2040,6 +2048,7 @@"Save memory suggestions": "Guardar sugerencias de memoria","Save network proxy": "Guardar proxy de red","Save settings": "Guardar configuración",+ "Save subtitles": "Guardar subtítulos","Save text source": "Guardar fuente de texto","Save to local draft": "Guardar en borrador local","Save {{0}} subtitles": "Guardar {{0}} subtítulos",@@ -2208,6 +2217,7 @@"Source record missing: {{0}}": "Falta el registro fuente: {{0}}","Source subtitles": "Subtítulos fuente","Source subtitles (skip transcription)": "Subtítulos de origen (omitir transcripción)",+ "Source type": "Tipo de material","Source video": "Vídeo fuente","Source video downloaded": "Vídeo fuente descargado","Source video preparation failed. Existing subtitles remain editable and downloadable.": "Error en la preparación del vídeo fuente. Los subtítulos existentes siguen siendo editables y descargables.",@@ -2290,6 +2300,7 @@"Submitting the video generation task": "Enviar la tarea de generación de video","Submitting to the image provider": "Enviar al proveedor de imágenes","Submitting to the provider": "Enviar al proveedor",+ "Subtitle Translation": "Traducción de subtítulos","Subtitle content": "Contenido de subtítulos","Subtitle file": "Archivo de subtítulos","Subtitle files": "Archivos de subtítulos",@@ -2310,6 +2321,7 @@"Subtitles are pending": "Los subtítulos están pendientes.","Subtitles generated using audio transcription because platform captions were unavailable": "Subtítulos generados mediante transcripción de audio porque los subtítulos de la plataforma no estaban disponibles","Subtitles have not been generated for this version": "No se han generado subtítulos para esta versión.",+ "Subtitles were saved; the project remains V{{0}}.": "Se guardaron los subtítulos; el proyecto sigue en V{{0}}.","Subtitles, dubbing, and lip sync": "Subtítulos, doblaje y sincronización labial.","Success last time": "Éxito la última vez","Suggested structure": "Estructura sugerida",@@ -2673,7 +2685,10 @@"Transcription model": "Modelo de transcripción","Transcription provider": "Proveedor de transcripción","Translate & Dub Video": "Traducir y doblar vídeos",+ "Translate subtitles": "Traducir subtítulos","Translate to": "Traducir a",+ "Translate video": "Traducir vídeo",+ "Translated SRT": "SRT traducido","Translated subtitles": "Subtítulos traducidos","Translated subtitles (skip transcription and translation)": "Subtítulos traducidos (omitir transcripción y traducción)","Translating subtitles": "Traducir subtítulos",@@ -3004,6 +3019,7 @@"Waiting for earlier formats": "Esperando formatos anteriores","Waiting for first run": "Esperando la primera ejecución","Waiting for local capabilities": "Esperando capacidades locales",+ "Waiting for subtitles": "Esperando subtítulos","Waiting for the local runtime": "Esperando el tiempo de ejecución local","Waiting for the video provider": "Esperando al proveedor de vídeo","Waiting to analyze": "Esperando a analizar",diff --git a/apps/web/src/i18n/locales/fr-FR.json b/apps/web/src/i18n/locales/fr-FR.jsonindex 6297394b..c657b681 100644--- a/apps/web/src/i18n/locales/fr-FR.json+++ b/apps/web/src/i18n/locales/fr-FR.json@@ -50,6 +50,7 @@"Add a video link": "Ajouter un lien vidéo","Add a video to translate first": "Ajouter une vidéo à traduire en premier","Add a writing topic or instruction when no inspiration is provided.": "Ajoutez un sujet d'écriture ou des instructions lorsqu'aucune inspiration n'est fournie.",+ "Add an SRT file to translate first": "Ajoutez d’abord un fichier SRT à traduire","Add content priorities, subject details, or layout requirements": "Ajoutez des priorités de contenu, des détails sur le sujet ou des exigences de mise en page","Add context": "Ajouter du contexte","Add file": "Ajouter un fichier",@@ -62,6 +63,8 @@"Add one link at a time.": "Ajoutez un lien à la fois.","Add reference": "Ajouter une référence","Add reference image": "Ajouter une image de référence",+ "Add source": "Ajouter un contenu source",+ "Add subtitles": "Ajouter des sous-titres","Add to queue": "Ajouter à la file d'attente","Add variables": "Ajouter des variables","Add video": "Ajouter une vidéo",@@ -223,6 +226,7 @@"Auto-clip now": "Découpage automatique maintenant","Auto-match voice": "Correspondance automatique de la voix","Automatic": "Automatique",+ "Automatic captions": "Sous-titres automatiques","Automatically render up to {{0}} standalone video clips": "Rendu automatique jusqu'à {{0}} clips vidéo autonomes","Available": "Disponible","Available credits": "Crédits disponibles",@@ -248,6 +252,7 @@"Below": "Ci-dessous","Bilibili": "Bilibili","Bilibili video": "Vidéo Bilibili",+ "Bilingual SRT": "SRT bilingue","Bilingual subtitles": "Sous-titres bilingues","Bilingual · translation {{0}}": "Bilingue · traduction {{0}}","Billing and recharge history": "Historique de facturation et de recharge",@@ -1401,6 +1406,7 @@"Manage projects": "Gérer des projets","Manage this in MCP settings": "Gérez cela dans les paramètres MCP","Managed installation unavailable on this platform": "Installation gérée indisponible sur cette plateforme",+ "Manual subtitles": "Sous-titres manuels","Manual update checks are coming soon": "Les vérifications manuelles des mises à jour seront bientôt disponibles","Many": "Beaucoup","Maps / Charts": "Cartes / Graphiques",@@ -1901,6 +1907,7 @@"Remove reference": "Supprimer la référence","Remove reference image": "Supprimer l'image de référence","Remove sensitive information before use.": "Supprimez les informations sensibles avant utilisation.",+ "Remove subtitles": "Retirer les sous-titres","Remove {{0}}": "Supprimer {{0}}","Removed projects": "Projets supprimés","Rename": "Rebaptiser",@@ -1919,6 +1926,7 @@"Rendering video clips automatically": "Rendu automatique des clips vidéo","Repair folder": "Dossier de réparation","Repeat": "Répéter",+ "Replace file": "Changer de fichier","Replace image": "Remplacer l'image","Replace reference": "Remplacer la référence","Replaceable variable": "Variable remplaçable",@@ -2040,6 +2048,7 @@"Save memory suggestions": "Enregistrer les suggestions de mémoire","Save network proxy": "Enregistrer le proxy réseau","Save settings": "Enregistrer les paramètres",+ "Save subtitles": "Enregistrer les sous-titres","Save text source": "Enregistrer la source du texte","Save to local draft": "Enregistrer dans le brouillon local","Save {{0}} subtitles": "Enregistrer {{0}} sous-titres",@@ -2208,6 +2217,7 @@"Source record missing: {{0}}": "Enregistrement source manquant : {{0}}","Source subtitles": "Sous-titres sources","Source subtitles (skip transcription)": "Sous-titres sources (ignorer la transcription)",+ "Source type": "Type de contenu source","Source video": "Vidéo source","Source video downloaded": "Vidéo source téléchargée","Source video preparation failed. Existing subtitles remain editable and downloadable.": "La préparation de la vidéo source a échoué. Les sous-titres existants restent modifiables et téléchargeables.",@@ -2290,6 +2300,7 @@"Submitting the video generation task": "Soumission de la tâche de génération vidéo","Submitting to the image provider": "Soumission au fournisseur d'images","Submitting to the provider": "Soumission au fournisseur",+ "Subtitle Translation": "Traduction de sous-titres","Subtitle content": "Contenu des sous-titres","Subtitle file": "Fichier de sous-titres","Subtitle files": "Fichiers de sous-titres",@@ -2310,6 +2321,7 @@"Subtitles are pending": "Les sous-titres sont en attente","Subtitles generated using audio transcription because platform captions were unavailable": "Sous-titres générés à l'aide de la transcription audio, car les sous-titres de la plateforme n'étaient pas disponibles","Subtitles have not been generated for this version": "Les sous-titres n'ont pas été générés pour cette version",+ "Subtitles were saved; the project remains V{{0}}.": "Les sous-titres ont été enregistrés ; le projet reste en V{{0}}.","Subtitles, dubbing, and lip sync": "Sous-titres, doublage et synchronisation labiale","Success last time": "Succès la dernière fois","Suggested structure": "Structure suggérée",@@ -2673,7 +2685,10 @@"Transcription model": "Modèle de transcription","Transcription provider": "Fournisseur de transcription","Translate & Dub Video": "Traduire et doubler une vidéo",+ "Translate subtitles": "Traduire les sous-titres","Translate to": "Traduire en",+ "Translate video": "Traduire la vidéo",+ "Translated SRT": "SRT traduit","Translated subtitles": "Sous-titres traduits","Translated subtitles (skip transcription and translation)": "Sous-titres traduits (ignorer la transcription et la traduction)","Translating subtitles": "Traduire les sous-titres",@@ -3004,6 +3019,7 @@"Waiting for earlier formats": "En attendant les formats antérieurs","Waiting for first run": "En attente du premier run","Waiting for local capabilities": "En attente de capacités locales",+ "Waiting for subtitles": "En attente de sous-titres","Waiting for the local runtime": "En attente du runtime local","Waiting for the video provider": "En attente du fournisseur vidéo","Waiting to analyze": "En attendant d'analyser",diff --git a/apps/web/src/i18n/locales/ja-JP.json b/apps/web/src/i18n/locales/ja-JP.jsonindex d2bd366d..c330f01e 100644--- a/apps/web/src/i18n/locales/ja-JP.json+++ b/apps/web/src/i18n/locales/ja-JP.json@@ -50,6 +50,7 @@"Add a video link": "ビデオリンクを追加する","Add a video to translate first": "最初に翻訳するビデオを追加してください","Add a writing topic or instruction when no inspiration is provided.": "インスピレーションが得られない場合は、書くトピックや指示を追加します。",+ "Add an SRT file to translate first": "翻訳する SRT ファイルを先に追加してください","Add content priorities, subject details, or layout requirements": "コンテンツの優先順位、件名の詳細、またはレイアウト要件を追加します","Add context": "コンテキストを追加する","Add file": "ファイルを追加",@@ -62,6 +63,8 @@"Add one link at a time.": "リンクは一度に 1 つずつ追加します。","Add reference": "参照の追加","Add reference image": "参考画像を追加",+ "Add source": "素材を追加",+ "Add subtitles": "字幕を追加","Add to queue": "キューに追加","Add variables": "変数の追加","Add video": "ビデオを追加",@@ -223,6 +226,7 @@"Auto-clip now": "今すぐ自動クリップ","Auto-match voice": "音声を自動でマッチング","Automatic": "自動",+ "Automatic captions": "自動字幕","Automatically render up to {{0}} standalone video clips": "最大 {{0}} 個のスタンドアロン ビデオ クリップを自動的にレンダリングします","Available": "利用可能","Available credits": "利用可能なクレジット",@@ -248,6 +252,7 @@"Below": "下に","Bilibili": "ビリビリ","Bilibili video": "ビリビリ動画",+ "Bilingual SRT": "二言語 SRT","Bilingual subtitles": "バイリンガル字幕","Bilingual · translation {{0}}": "バイリンガル · 翻訳 {{0}}","Billing and recharge history": "請求とリチャージ履歴",@@ -1401,6 +1406,7 @@"Manage projects": "プロジェクトを管理する","Manage this in MCP settings": "これは MCP 設定で管理します","Managed installation unavailable on this platform": "このプラットフォームでは管理されたインストールは利用できません",+ "Manual subtitles": "手動字幕","Manual update checks are coming soon": "手動更新チェックは近日中に行われる予定です","Many": "多くの","Maps / Charts": "地図/チャート",@@ -1901,6 +1907,7 @@"Remove reference": "参照の削除","Remove reference image": "参照画像を削除する","Remove sensitive information before use.": "機密情報は使用前に削除してください。",+ "Remove subtitles": "字幕を削除","Remove {{0}}": "{{0}}を削除","Removed projects": "削除されたプロジェクト","Rename": "名前の変更",@@ -1919,6 +1926,7 @@"Rendering video clips automatically": "ビデオクリップを自動的にレンダリングする","Repair folder": "修復フォルダー","Repeat": "繰り返す",+ "Replace file": "ファイルを変更","Replace image": "画像を置き換える","Replace reference": "参照を置き換える","Replaceable variable": "置換可能な変数",@@ -2040,6 +2048,7 @@"Save memory suggestions": "メモリの保存に関する提案","Save network proxy": "ネットワークプロキシの保存","Save settings": "設定を保存する",+ "Save subtitles": "字幕を保存","Save text source": "テキストソースを保存する","Save to local draft": "ローカルドラフトに保存","Save {{0}} subtitles": "{{0}} 個の字幕を保存",@@ -2208,6 +2217,7 @@"Source record missing: {{0}}": "ソース レコードが見つかりません: {{0}}","Source subtitles": "ソース字幕","Source subtitles (skip transcription)": "ソース字幕 (転写をスキップ)",+ "Source type": "素材の種類","Source video": "ソースビデオ","Source video downloaded": "ダウンロードされたソースビデオ","Source video preparation failed. Existing subtitles remain editable and downloadable.": "ソースビデオの準備に失敗しました。既存の字幕は引き続き編集およびダウンロードできます。",@@ -2290,6 +2300,7 @@"Submitting the video generation task": "ビデオ生成タスクの送信","Submitting to the image provider": "画像プロバイダーに送信する","Submitting to the provider": "プロバイダーに提出する",+ "Subtitle Translation": "字幕翻訳","Subtitle content": "字幕の内容","Subtitle file": "字幕ファイル","Subtitle files": "字幕ファイル",@@ -2310,6 +2321,7 @@"Subtitles are pending": "字幕は保留中です","Subtitles generated using audio transcription because platform captions were unavailable": "プラットフォームのキャプションが利用できないため、音声転写を使用して字幕が生成されました","Subtitles have not been generated for this version": "このバージョンでは字幕が生成されていません",+ "Subtitles were saved; the project remains V{{0}}.": "字幕を保存しました。プロジェクトは V{{0}} のままです。","Subtitles, dubbing, and lip sync": "字幕、吹き替え、リップシンク","Success last time": "前回は成功","Suggested structure": "提案される構造",@@ -2673,7 +2685,10 @@"Transcription model": "転写モデル","Transcription provider": "文字起こしプロバイダー","Translate & Dub Video": "ビデオの翻訳と吹き替え",+ "Translate subtitles": "字幕を翻訳","Translate to": "に翻訳する",+ "Translate video": "動画を翻訳",+ "Translated SRT": "翻訳済み SRT","Translated subtitles": "翻訳された字幕","Translated subtitles (skip transcription and translation)": "翻訳された字幕 (文字起こしと翻訳をスキップ)","Translating subtitles": "字幕の翻訳",@@ -3004,6 +3019,7 @@"Waiting for earlier formats": "以前の形式を待っています","Waiting for first run": "最初の実行を待っています","Waiting for local capabilities": "ローカル機能を待っています",+ "Waiting for subtitles": "字幕のアップロード待ち","Waiting for the local runtime": "ローカルランタイムを待っています","Waiting for the video provider": "ビデオプロバイダーを待っています","Waiting to analyze": "分析を待っています",diff --git a/apps/web/src/i18n/locales/ko-KR.json b/apps/web/src/i18n/locales/ko-KR.jsonindex 60f9baa0..4491fba7 100644--- a/apps/web/src/i18n/locales/ko-KR.json+++ b/apps/web/src/i18n/locales/ko-KR.json@@ -50,6 +50,7 @@"Add a video link": "비디오 링크 추가","Add a video to translate first": "먼저 번역할 동영상을 추가하세요.","Add a writing topic or instruction when no inspiration is provided.": "영감이 제공되지 않는 경우 글쓰기 주제나 지침을 추가하세요.",+ "Add an SRT file to translate first": "먼저 번역할 SRT 파일을 추가하세요","Add content priorities, subject details, or layout requirements": "콘텐츠 우선순위, 주제 세부정보 또는 레이아웃 요구사항 추가","Add context": "컨텍스트 추가","Add file": "파일 추가",@@ -62,6 +63,8 @@"Add one link at a time.": "한 번에 하나의 링크를 추가하세요.","Add reference": "참조 추가","Add reference image": "참조 이미지 추가",+ "Add source": "소재 추가",+ "Add subtitles": "자막 추가","Add to queue": "대기열에 추가","Add variables": "변수 추가","Add video": "비디오 추가",@@ -223,6 +226,7 @@"Auto-clip now": "지금 자동 클립","Auto-match voice": "음성 자동 일치","Automatic": "오토매틱",+ "Automatic captions": "자동 자막","Automatically render up to {{0}} standalone video clips": "최대 {{0}}개의 독립형 비디오 클립을 자동으로 렌더링합니다.","Available": "사용 가능","Available credits": "사용 가능한 크레딧",@@ -248,6 +252,7 @@"Below": "아래에","Bilibili": "빌리빌리","Bilibili video": "빌리빌리 비디오",+ "Bilingual SRT": "이중 언어 SRT","Bilingual subtitles": "이중 언어 자막","Bilingual · translation {{0}}": "이중 언어 · 번역 {{0}}","Billing and recharge history": "결제 및 충전 내역",@@ -1401,6 +1406,7 @@"Manage projects": "프로젝트 관리","Manage this in MCP settings": "MCP 설정에서 관리하세요","Managed installation unavailable on this platform": "이 플랫폼에서는 관리형 설치를 사용할 수 없습니다.",+ "Manual subtitles": "수동 자막","Manual update checks are coming soon": "수동 업데이트 확인이 곧 제공될 예정입니다.","Many": "많은","Maps / Charts": "지도/차트",@@ -1901,6 +1907,7 @@"Remove reference": "참조 삭제","Remove reference image": "참조 이미지 삭제","Remove sensitive information before use.": "사용하기 전에 민감한 정보를 제거하십시오.",+ "Remove subtitles": "자막 제거","Remove {{0}}": "{{0}} 삭제","Removed projects": "삭제된 프로젝트","Rename": "이름 바꾸기",@@ -1919,6 +1926,7 @@"Rendering video clips automatically": "비디오 클립 자동 렌더링","Repair folder": "폴더 복구","Repeat": "반복하다",+ "Replace file": "파일 변경","Replace image": "이미지 교체","Replace reference": "참조 교체","Replaceable variable": "교체 가능한 변수",@@ -2040,6 +2048,7 @@"Save memory suggestions": "메모리 제안 저장","Save network proxy": "네트워크 프록시 저장","Save settings": "설정 저장",+ "Save subtitles": "자막 저장","Save text source": "텍스트 소스 저장","Save to local draft": "로컬 초안에 저장","Save {{0}} subtitles": "{{0}}개의 자막 저장",@@ -2208,6 +2217,7 @@"Source record missing: {{0}}": "소스 레코드 누락: {{0}}","Source subtitles": "소스 자막","Source subtitles (skip transcription)": "소스 자막(녹화 건너뛰기)",+ "Source type": "소재 유형","Source video": "소스 비디오","Source video downloaded": "소스 비디오가 다운로드됨","Source video preparation failed. Existing subtitles remain editable and downloadable.": "소스 비디오 준비에 실패했습니다. 기존 자막은 편집 및 다운로드가 가능한 상태로 유지됩니다.",@@ -2290,6 +2300,7 @@"Submitting the video generation task": "비디오 생성 작업 제출","Submitting to the image provider": "이미지 제공업체에 제출 중","Submitting to the provider": "공급자에게 제출",+ "Subtitle Translation": "자막 번역","Subtitle content": "자막 내용","Subtitle file": "자막 파일","Subtitle files": "자막 파일",@@ -2310,6 +2321,7 @@"Subtitles are pending": "자막이 대기 중입니다.","Subtitles generated using audio transcription because platform captions were unavailable": "플랫폼 캡션을 사용할 수 없기 때문에 오디오 텍스트 변환을 사용하여 자막이 생성되었습니다.","Subtitles have not been generated for this version": "이 버전에 대한 자막이 생성되지 않았습니다.",+ "Subtitles were saved; the project remains V{{0}}.": "자막이 저장되었습니다. 프로젝트는 V{{0}}로 유지됩니다.","Subtitles, dubbing, and lip sync": "자막, 더빙, 립싱크","Success last time": "저번에 성공","Suggested structure": "제안된 구조",@@ -2673,7 +2685,10 @@"Transcription model": "전사 모델","Transcription provider": "전사 제공업체","Translate & Dub Video": "비디오 번역 및 더빙",+ "Translate subtitles": "자막 번역","Translate to": "다음으로 번역하다",+ "Translate video": "동영상 번역",+ "Translated SRT": "번역된 SRT","Translated subtitles": "번역된 자막","Translated subtitles (skip transcription and translation)": "번역된 자막(녹화 및 번역 건너뛰기)","Translating subtitles": "자막 번역",@@ -3004,6 +3019,7 @@"Waiting for earlier formats": "이전 형식을 기다리는 중","Waiting for first run": "첫 실행을 기다리는 중","Waiting for local capabilities": "현지 역량을 기다리는 중",+ "Waiting for subtitles": "자막 업로드 대기 중","Waiting for the local runtime": "로컬 런타임을 기다리는 중","Waiting for the video provider": "영상 제공자를 기다리는 중","Waiting to analyze": "분석 대기 중",diff --git a/apps/web/src/i18n/locales/pt-BR.json b/apps/web/src/i18n/locales/pt-BR.jsonindex 1121734d..e4b5f106 100644--- a/apps/web/src/i18n/locales/pt-BR.json+++ b/apps/web/src/i18n/locales/pt-BR.json@@ -50,6 +50,7 @@"Add a video link": "Adicione um link de vídeo","Add a video to translate first": "Adicione um vídeo para traduzir primeiro","Add a writing topic or instruction when no inspiration is provided.": "Adicione um tópico de redação ou instrução quando nenhuma inspiração for fornecida.",+ "Add an SRT file to translate first": "Adicione primeiro um arquivo SRT para traduzir","Add content priorities, subject details, or layout requirements": "Adicione prioridades de conteúdo, detalhes de assunto ou requisitos de layout","Add context": "Adicionar contexto","Add file": "Adicionar arquivo",@@ -62,6 +63,8 @@"Add one link at a time.": "Adicione um link de cada vez.","Add reference": "Adicionar referência","Add reference image": "Adicionar imagem de referência",+ "Add source": "Adicionar material",+ "Add subtitles": "Adicionar legendas","Add to queue": "Adicionar à fila","Add variables": "Adicionar variáveis","Add video": "Adicionar vídeo",@@ -223,6 +226,7 @@"Auto-clip now": "Clipe automático agora","Auto-match voice": "Correspondência automática de voz","Automatic": "Automático",+ "Automatic captions": "Legendas automáticas","Automatically render up to {{0}} standalone video clips": "Renderizar automaticamente até {{0}} videoclipes independentes","Available": "Disponível","Available credits": "Créditos disponíveis",@@ -248,6 +252,7 @@"Below": "Abaixo","Bilibili": "Bilíbili","Bilibili video": "Vídeo de bilibili",+ "Bilingual SRT": "SRT bilíngue","Bilingual subtitles": "Legendas bilíngues","Bilingual · translation {{0}}": "Bilíngue · tradução {{0}}","Billing and recharge history": "Histórico de faturamento e recarga",@@ -1401,6 +1406,7 @@"Manage projects": "Gerenciar projetos","Manage this in MCP settings": "Gerencie isso nas configurações do MCP","Managed installation unavailable on this platform": "Instalação gerenciada indisponível nesta plataforma",+ "Manual subtitles": "Legendas manuais","Manual update checks are coming soon": "Verificações manuais de atualização chegarão em breve","Many": "Muitos","Maps / Charts": "Mapas / Gráficos",@@ -1901,6 +1907,7 @@"Remove reference": "Remover referência","Remove reference image": "Remover imagem de referência","Remove sensitive information before use.": "Remova informações confidenciais antes de usar.",+ "Remove subtitles": "Remover legendas","Remove {{0}}": "Remover {{0}}","Removed projects": "Projetos removidos","Rename": "Renomear",@@ -1919,6 +1926,7 @@"Rendering video clips automatically": "Renderizando videoclipes automaticamente","Repair folder": "Pasta de reparo","Repeat": "Repita",+ "Replace file": "Trocar arquivo","Replace image": "Substituir imagem","Replace reference": "Substituir referência","Replaceable variable": "Variável substituível",@@ -2040,6 +2048,7 @@"Save memory suggestions": "Salvar sugestões de memória","Save network proxy": "Salvar proxy de rede","Save settings": "Salvar configurações",+ "Save subtitles": "Salvar legendas","Save text source": "Salvar fonte do texto","Save to local draft": "Salvar no rascunho local","Save {{0}} subtitles": "Salvar {{0}} legendas",@@ -2208,6 +2217,7 @@"Source record missing: {{0}}": "Registro de origem ausente: {{0}}","Source subtitles": "Legendas de origem","Source subtitles (skip transcription)": "Legendas originais (pular transcrição)",+ "Source type": "Tipo de material","Source video": "Vídeo fonte","Source video downloaded": "Vídeo fonte baixado","Source video preparation failed. Existing subtitles remain editable and downloadable.": "Falha na preparação do vídeo de origem. As legendas existentes permanecem editáveis e disponíveis para download.",@@ -2290,6 +2300,7 @@"Submitting the video generation task": "Enviando a tarefa de geração de vídeo","Submitting to the image provider": "Enviando para o provedor de imagem","Submitting to the provider": "Enviando para o provedor",+ "Subtitle Translation": "Tradução de legendas","Subtitle content": "Conteúdo da legenda","Subtitle file": "Arquivo de legenda","Subtitle files": "Arquivos de legenda",@@ -2310,6 +2321,7 @@"Subtitles are pending": "As legendas estão pendentes","Subtitles generated using audio transcription because platform captions were unavailable": "Legendas geradas usando transcrição de áudio porque as legendas da plataforma não estavam disponíveis","Subtitles have not been generated for this version": "As legendas não foram geradas para esta versão",+ "Subtitles were saved; the project remains V{{0}}.": "As legendas foram salvas; o projeto continua na V{{0}}.","Subtitles, dubbing, and lip sync": "Legendas, dublagem e sincronização labial","Success last time": "Sucesso da última vez","Suggested structure": "Estrutura sugerida",@@ -2673,7 +2685,10 @@"Transcription model": "Modelo de transcrição","Transcription provider": "Provedor de transcrição","Translate & Dub Video": "Traduzir e dublar vídeo",+ "Translate subtitles": "Traduzir legendas","Translate to": "Traduzir para",+ "Translate video": "Traduzir vídeo",+ "Translated SRT": "SRT traduzido","Translated subtitles": "Legendas traduzidas","Translated subtitles (skip transcription and translation)": "Legendas traduzidas (pular transcrição e tradução)","Translating subtitles": "Traduzindo legendas",@@ -3004,6 +3019,7 @@"Waiting for earlier formats": "Aguardando formatos anteriores","Waiting for first run": "Aguardando a primeira execução","Waiting for local capabilities": "Aguardando recursos locais",+ "Waiting for subtitles": "Aguardando legendas","Waiting for the local runtime": "Aguardando o tempo de execução local","Waiting for the video provider": "Aguardando o provedor de vídeo","Waiting to analyze": "Esperando para analisar",diff --git a/apps/web/src/i18n/locales/sv-SE.json b/apps/web/src/i18n/locales/sv-SE.jsonindex fc8d97b2..4cc57be4 100644--- a/apps/web/src/i18n/locales/sv-SE.json+++ b/apps/web/src/i18n/locales/sv-SE.json@@ -50,6 +50,7 @@"Add a video link": "Lägg till en videolänk","Add a video to translate first": "Lägg till en video att översätta först","Add a writing topic or instruction when no inspiration is provided.": "Lägg till ett skrivämne eller en instruktion när ingen inspiration tillhandahålls.",+ "Add an SRT file to translate first": "Lägg till en SRT-fil att översätta först","Add content priorities, subject details, or layout requirements": "Lägg till innehållsprioriteringar, ämnesdetaljer eller layoutkrav","Add context": "Lägg till sammanhang","Add file": "Lägg till fil",@@ -62,6 +63,8 @@"Add one link at a time.": "Lägg till en länk i taget.","Add reference": "Lägg till referens","Add reference image": "Lägg till referensbild",+ "Add source": "Lägg till material",+ "Add subtitles": "Lägg till undertexter","Add to queue": "Lägg till i kö","Add variables": "Lägg till variabler","Add video": "Lägg till video",@@ -223,6 +226,7 @@"Auto-clip now": "Autoklipp nu","Auto-match voice": "Automatcha röst","Automatic": "Automatisk",+ "Automatic captions": "Automatiska undertexter","Automatically render up to {{0}} standalone video clips": "Rendera automatiskt upp till {{0}} fristående videoklipp","Available": "Tillgänglig","Available credits": "Tillgängliga poäng",@@ -248,6 +252,7 @@"Below": "Nedan","Bilibili": "Bilibili","Bilibili video": "Bilibili video",+ "Bilingual SRT": "Tvåspråkig SRT","Bilingual subtitles": "Tvåspråkiga undertexter","Bilingual · translation {{0}}": "Tvåspråkig · översättning {{0}}","Billing and recharge history": "Fakturerings- och laddningshistorik",@@ -1401,6 +1406,7 @@"Manage projects": "Hantera projekt","Manage this in MCP settings": "Hantera detta i MCP-inställningar","Managed installation unavailable on this platform": "Hanterad installation är inte tillgänglig på den här plattformen",+ "Manual subtitles": "Manuella undertexter","Manual update checks are coming soon": "Manuella uppdateringskontroller kommer snart","Many": "Många","Maps / Charts": "Kartor / sjökort",@@ -1901,6 +1907,7 @@"Remove reference": "Ta bort referens","Remove reference image": "Ta bort referensbild","Remove sensitive information before use.": "Ta bort känslig information före användning.",+ "Remove subtitles": "Ta bort undertexter","Remove {{0}}": "Ta bort {{0}}","Removed projects": "Tog bort projekt","Rename": "Döpa om",@@ -1919,6 +1926,7 @@"Rendering video clips automatically": "Rendera videoklipp automatiskt","Repair folder": "Reparationsmapp","Repeat": "Upprepa",+ "Replace file": "Byt fil","Replace image": "Byt ut bild","Replace reference": "Byt ut referens","Replaceable variable": "Utbytbar variabel",@@ -2040,6 +2048,7 @@"Save memory suggestions": "Spara minnesförslag","Save network proxy": "Spara nätverksproxy","Save settings": "Spara inställningar",+ "Save subtitles": "Spara undertexter","Save text source": "Spara textkälla","Save to local draft": "Spara till lokalt utkast","Save {{0}} subtitles": "Spara {{0}} undertexter",@@ -2208,6 +2217,7 @@"Source record missing: {{0}}": "Källpost saknas: {{0}}","Source subtitles": "Källa undertexter","Source subtitles (skip transcription)": "Källundertexter (hoppa över transkription)",+ "Source type": "Materialtyp","Source video": "Källvideo","Source video downloaded": "Källvideo nedladdad","Source video preparation failed. Existing subtitles remain editable and downloadable.": "Förberedelse av källvideo misslyckades. Befintliga undertexter förblir redigerbara och nedladdningsbara.",@@ -2290,6 +2300,7 @@"Submitting the video generation task": "Skickar in videogenereringsuppgiften","Submitting to the image provider": "Skickar till bildleverantören","Submitting to the provider": "Skickar till leverantören",+ "Subtitle Translation": "Undertextöversättning","Subtitle content": "Undertextinnehåll","Subtitle file": "Undertextfil","Subtitle files": "Undertextfiler",@@ -2310,6 +2321,7 @@"Subtitles are pending": "Undertexter väntar","Subtitles generated using audio transcription because platform captions were unavailable": "Undertexter genererades med ljudtranskription eftersom plattformstextning inte var tillgänglig","Subtitles have not been generated for this version": "Undertexter har inte skapats för den här versionen",+ "Subtitles were saved; the project remains V{{0}}.": "Undertexterna har sparats; projektet är fortfarande V{{0}}.","Subtitles, dubbing, and lip sync": "Undertexter, dubbning och läppsynkronisering","Success last time": "Framgång förra gången","Suggested structure": "Föreslagen struktur",@@ -2673,7 +2685,10 @@"Transcription model": "Transkriptionsmodell","Transcription provider": "Transkriptionsleverantör","Translate & Dub Video": "Översätt och kopiera video",+ "Translate subtitles": "Översätt undertexter","Translate to": "Översätt till",+ "Translate video": "Översätt video",+ "Translated SRT": "Översatt SRT","Translated subtitles": "Översatta undertexter","Translated subtitles (skip transcription and translation)": "Översatta undertexter (hoppa över transkription och översättning)","Translating subtitles": "Översätta undertexter",@@ -3004,6 +3019,7 @@"Waiting for earlier formats": "Väntar på tidigare format","Waiting for first run": "Väntar på första körningen","Waiting for local capabilities": "Väntar på lokala förmågor",+ "Waiting for subtitles": "Väntar på undertexter","Waiting for the local runtime": "Väntar på den lokala körtiden","Waiting for the video provider": "Väntar på videoleverantören","Waiting to analyze": "Väntar på att analysera",diff --git a/apps/web/src/i18n/translated-copy.test.ts b/apps/web/src/i18n/translated-copy.test.tsindex 67ad5702..9e64ad01 100644--- a/apps/web/src/i18n/translated-copy.test.ts+++ b/apps/web/src/i18n/translated-copy.test.ts@@ -3,6 +3,23 @@ import { additionalLanguageCatalogs, translateEnglishCopy } from './translated-cimport type { AppLanguage } from './language.js';describe('additional language catalogs', () => {+ it('covers subtitle translation and download messages in every additional language', () => {+ const messages = [+ 'Add an SRT file to translate first', 'Add source', 'Add subtitles', 'Automatic captions',+ 'Bilingual SRT', 'Manual subtitles', 'Remove subtitles', 'Replace file', 'Save subtitles',+ 'Source type', 'Subtitle Translation', 'Subtitles were saved; the project remains V{{0}}.',+ 'Translate subtitles', 'Translate video', 'Translated SRT', 'Waiting for subtitles'+ ];+ for (const [language, catalog] of Object.entries(additionalLanguageCatalogs)) {+ for (const message of messages) {+ expect(Object.hasOwn(catalog!, message), `${language}: ${message}`).toBe(true);+ expect(translateEnglishCopy(language as AppLanguage, message)).not.toBe(message);+ }+ expect(translateEnglishCopy(language as AppLanguage, 'Subtitles were saved; the project remains V12.'))+ .toBe(catalog!['Subtitles were saved; the project remains V{{0}}.']!.replace('{{0}}', '12'));+ }+ });+it.each([['ja-JP', '取得'], ['ko-KR', '가져오기'], ['es-ES', 'Obtener'],['fr-FR', 'Récupérer'], ['de-DE', 'Abrufen'], ['pt-BR', 'Obter']diff --git a/packages/protocol/src/creator-download.ts b/packages/protocol/src/creator-download.tsindex fe45fc22..f1559519 100644--- a/packages/protocol/src/creator-download.ts+++ b/packages/protocol/src/creator-download.ts@@ -91,15 +91,18 @@ function isRedditVideoUrl(url: URL): boolean {|| /^\/r\/[\w-]+\/s\/[a-z0-9]+\/?$/i.test(url.pathname));}-export type DownloadMediaType = 'video' | 'audio';+export type DownloadMediaType = 'video' | 'audio' | 'subtitle';-export type DownloadContainer = 'mp4' | 'mp3' | 'm4a' | 'webm';+export type DownloadContainer = 'mp4' | 'mp3' | 'm4a' | 'webm' | 'srt';export type DownloadOption = {id: string;mediaType: DownloadMediaType;container: DownloadContainer;audioLanguage?: string;+ subtitleLanguage?: string;+ subtitleName?: string;+ subtitleSource?: 'manual' | 'automatic';width?: number;height?: number;fps?: number;diff --git a/runtime/krillinai/internal/cli/commands.go b/runtime/krillinai/internal/cli/commands.goindex 9d0e9583..546e8c54 100644--- a/runtime/krillinai/internal/cli/commands.go+++ b/runtime/krillinai/internal/cli/commands.go@@ -112,7 +112,7 @@ func Help(cmd Command) string {switch cmd.Name {case "subtitle":return `Usage:- krillinai-cli subtitle <input> --origin-lang <lang> --target-lang <lang> --workdir <dir> [flags]+ krillinai-cli subtitle [input] --origin-lang <lang> --target-lang <lang> --workdir <dir> [flags]Flags:--origin-lang <lang> Source language, such as en, zh, ja@@ -521,8 +521,8 @@ func parseSubtitle(name string, args []string) (Command, error) {if input == "" && fs.NArg() == 1 {input = fs.Arg(0)}- if input == "" || fs.NArg() > 1 {- return Command{}, errors.New("subtitle requires input")+ if (input == "" && (*inputSRT == "" || *prepareVideo)) || fs.NArg() > 1 {+ return Command{}, errors.New("subtitle requires input or --input-srt (video preparation requires input)")}return Command{Name: name,diff --git a/runtime/krillinai/internal/cli/commands_test.go b/runtime/krillinai/internal/cli/commands_test.goindex 9569d909..cba47a6b 100644--- a/runtime/krillinai/internal/cli/commands_test.go+++ b/runtime/krillinai/internal/cli/commands_test.go@@ -37,6 +37,18 @@ func TestParseSubtitleCommand(t *testing.T) {}}+func TestParseStandaloneSRT(t *testing.T) {+ cmd, err := Parse([]string{"subtitle", "--input-srt", "source.srt", "--origin-lang", "en", "--target-lang", "zh_cn"})+ if err != nil || cmd.Subtitle.Input != "" || cmd.Subtitle.InputSRT != "source.srt" || cmd.Subtitle.PrepareVideo {+ t.Fatalf("command = %+v, error = %v", cmd, err)+ }+ for _, args := range [][]string{{"subtitle"}, {"subtitle", "--input-srt", "source.srt", "--prepare-video"}} {+ if _, err := Parse(args); err == nil {+ t.Fatalf("expected missing video error for %v", args)+ }+ }+}+func TestParseDeferredMediaAndAudioOnlyOptions(t *testing.T) {cmd, err := Parse([]string{"tts", "--input-srt", "target.srt", "--audio-only", "--source-url", "https://www.youtube.com/watch?v=demo", "--media-workdir", "source-cache"})if err != nil || !cmd.TTS.AudioOnly || cmd.TTS.SourceURL == "" || cmd.TTS.MediaWorkdir != "source-cache" {diff --git a/runtime/krillinai/internal/pipeline/subtitle_test.go b/runtime/krillinai/internal/pipeline/subtitle_test.goindex 2aaf9721..fbb4e9cc 100644--- a/runtime/krillinai/internal/pipeline/subtitle_test.go+++ b/runtime/krillinai/internal/pipeline/subtitle_test.go@@ -72,6 +72,32 @@ func TestImportedSubtitlesSkipRecognitionAndPreserveMultilineText(t *testing.T)}}+func TestStandaloneSRTTranslatesWithoutMediaAndPreservesTimeline(t *testing.T) {+ root := t.TempDir()+ path := filepath.Join(root, "source.srt")+ content := "1\n00:00:02,250 --> 00:00:04,750\nHello\nworld\n\n2\n00:00:05,000 --> 00:00:06,500\nNext cue\n"+ if err := os.WriteFile(path, []byte(content), 0600); err != nil {+ t.Fatal(err)+ }+ fake := &fakeStageService{}+ response, err := GenerateSubtitles(context.Background(), fake, SubtitleRequest{Workdir: root, TaskID: "srt-only", OriginLang: "en", TargetLang: "zh_cn", InputSRT: path})+ if err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(fake.calls, []string{"translate-import"}) {+ t.Fatalf("unexpected media or ASR calls: %v", fake.calls)+ }+ if response.Outputs.OriginVideo != "" {+ t.Fatalf("unexpected video: %+v", response.Outputs)+ }+ for _, output := range []string{response.Outputs.OriginSRT, response.Outputs.TargetSRT, response.Outputs.BilingualSRT} {+ data, err := os.ReadFile(output)+ if err != nil || !strings.Contains(string(data), "00:00:02,250 --> 00:00:04,750") || !strings.Contains(string(data), "00:00:05,000 --> 00:00:06,500") {+ t.Fatalf("timeline changed: %s, %v", data, err)+ }+ }+}+func fmtBool(value bool) string {if value {return "translated"