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
fix: normalize shifted subtitles and show clip errors as toasts
Joshua Yin Junxi7d8975429ba6
diff --git a/apps/web/src/features/dashboard/AutoClipWorkspace.tsx b/apps/web/src/features/dashboard/AutoClipWorkspace.tsxindex c2383ad8..c51fb432 100644--- a/apps/web/src/features/dashboard/AutoClipWorkspace.tsx+++ b/apps/web/src/features/dashboard/AutoClipWorkspace.tsx@@ -7,13 +7,15 @@ import {import { useEffect, useMemo, useRef, useState } from 'react';import {Check,+ CircleAlert,Download,FileVideo,Grid2X2,List as ListIcon,LoaderCircle,Scissors,- Sparkles+ Sparkles,+ X} from 'lucide-react';import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';import type { VideoMetadataService } from '../../services/video-metadata-service.js';@@ -80,6 +82,7 @@ export default function AutoClipWorkspace(props: {const [aspectRatio, setAspectRatio] = useState<ClipAspectRatio>(() => readAspectRatio(session?.state.aspectRatio));const [notice, setNotice] = useState('');const [error, setError] = useState('');+ const [dismissedErrorKey, setDismissedErrorKey] = useState('');const [currentStep, setCurrentStep] = useState<AutoClipStep>(0);const [furthestStep, setFurthestStep] = useState<AutoClipStep>(0);const [resultVersion, setResultVersion] = useState<number>();@@ -127,6 +130,14 @@ export default function AutoClipWorkspace(props: {const rendering = latestRenderStage?.status === 'queued' || latestRenderStage?.status === 'running';const runtimeError = latestFailedStage(session?.job.stages ?? []);const visibleError = error || formatClipError(runtimeError ?? session?.error, l);+ const technicalError = isTechnicalClipError(error || (runtimeError ?? session?.error));+ const technicalErrorKey = technicalError+ ? `${error ? 'local' : runtimeError?.id ?? 'session'}:${visibleError}`+ : '';+ const persistentError = technicalError ? '' : visibleError;+ const activeToast = technicalError && technicalErrorKey !== dismissedErrorKey+ ? { id: -1, message: visibleError }+ : null;const renderedArtifacts = useMemo(() => selectedResult === undefined? []@@ -146,6 +157,18 @@ export default function AutoClipWorkspace(props: {if (latestVersion !== undefined) setResultVersion(latestVersion);}, [latestVersion]);+ useEffect(() => {+ if (activeToast === null) return undefined;+ const timer = window.setTimeout(() => {+ setDismissedErrorKey(technicalErrorKey);+ }, 4_000);+ return () => window.clearTimeout(timer);+ }, [activeToast?.id, activeToast?.message, technicalErrorKey]);++ useEffect(() => {+ if (!technicalErrorKey) setDismissedErrorKey('');+ }, [technicalErrorKey]);+useEffect(() => {if (resultVersions.length === 0) return;setCurrentStep(2);@@ -381,7 +404,7 @@ export default function AutoClipWorkspace(props: {: currentStep === 2? l('切片结果', 'Clip results'): steps[currentStep]!}- currentIssue={visibleError || undefined}+ currentIssue={persistentError || undefined}onCancelTask={analyzing || rendering? () => void session?.cancelJob().catch(cause => setError(formatClipError(cause, l))): undefined}@@ -390,7 +413,18 @@ export default function AutoClipWorkspace(props: {: undefined}onBack={props.onBack}>- <div className="creator-tool-stack">+ <div className="creator-tool-stack auto-clip-tool-stack">+ {activeToast ? (+ <div className="creator-tool-toast" role="alert">+ <span aria-hidden="true"><CircleAlert size={17} /></span>+ <div><p>{activeToast.message}</p></div>+ <button type="button" aria-label={l('关闭提示', 'Dismiss notification')} onClick={() => {+ setDismissedErrorKey(technicalErrorKey);+ setError('');+ session?.clearError();+ }}><X size={15} /></button>+ </div>+ ) : null}<nav className="video-translation-steps creator-tool-steps" aria-label={l('视频切片流程', 'Video clip workflow')}><ol>{steps.map((step, index) => {const active = index === currentStep;@@ -1286,3 +1320,19 @@ function formatClipError(: '';return message || l('视频切片失败,请稍后重试', 'Video clipping failed. Try again later.');}++function isTechnicalClipError(error: unknown): boolean {+ const message = typeof error === 'string'+ ? error+ : error instanceof Error+ ? error.message+ : (() => {+ const candidate = error as { message?: unknown; errorMessage?: unknown } | null | undefined;+ return typeof candidate?.message === 'string'+ ? candidate.message+ : typeof candidate?.errorMessage === 'string'+ ? candidate.errorMessage+ : '';+ })();+ return /normalize timeline|invalid[_ ]srt(?: timestamp)?|target_language_srt\.srt/i.test(message);+}diff --git a/apps/web/src/features/dashboard/dashboard.css b/apps/web/src/features/dashboard/dashboard.cssindex 84274729..e7ae4d9c 100644--- a/apps/web/src/features/dashboard/dashboard.css+++ b/apps/web/src/features/dashboard/dashboard.css@@ -1421,6 +1421,10 @@margin: 0 auto;}+.auto-clip-tool-stack {+ position: relative;+}+.stickman-workspace-content {display: grid;min-height: 0;@@ -2531,6 +2535,7 @@row-gap: 0;}+.creator-tool-toast,.wechat-article-toast {position: absolute;z-index: 12;@@ -2552,6 +2557,7 @@box-sizing: border-box;}+.creator-tool-toast > span,.wechat-article-toast > span {width: 24px;height: 24px;@@ -2560,16 +2566,19 @@color: var(--danger);}+.creator-tool-toast[data-tone="success"] > span,.wechat-article-toast[data-tone="success"] > span {color: var(--success);}+.creator-tool-toast > div,.wechat-article-toast > div {min-width: 0;display: grid;gap: 3px;}+.creator-tool-toast p,.wechat-article-toast p {min-width: 0;color: var(--text);@@ -2577,6 +2586,7 @@line-height: 1.45;}+.creator-tool-toast a,.wechat-article-toast a {width: fit-content;color: var(--accent);@@ -2585,10 +2595,12 @@text-decoration: none;}+.creator-tool-toast a:hover,.wechat-article-toast a:hover {text-decoration: underline;}+.creator-tool-toast button,.wechat-article-toast button {width: 28px;height: 28px;@@ -2600,11 +2612,13 @@color: var(--muted);}+.creator-tool-toast button:hover,.wechat-article-toast button:hover {background: var(--surface-2);color: var(--text);}+.creator-tool-toast button:focus-visible,.wechat-article-toast button:focus-visible {outline: 2px solid var(--accent);outline-offset: 1px;diff --git a/runtime/krillinai/internal/service/srt_timeline.go b/runtime/krillinai/internal/service/srt_timeline.goindex 6fa1cb87..39f1b263 100644--- a/runtime/krillinai/internal/service/srt_timeline.go+++ b/runtime/krillinai/internal/service/srt_timeline.go@@ -84,7 +84,12 @@ func NormalizeSRTFile(path string, allowOverlaps bool) error {timeline := make([]*util.SrtBlock, len(blocks))for index, block := range blocks {- timeline[index] = &util.SrtBlock{Timestamp: strings.TrimSpace(block[1])}+ normalized, err := normalizeSRTBlockLayout(block)+ if err != nil {+ return fmt.Errorf("cue %d: %w", index+1, err)+ }+ blocks[index] = normalized+ timeline[index] = &util.SrtBlock{Timestamp: strings.TrimSpace(normalized[1])}}if err := normalizeSrtBlocks(timeline, allowOverlaps); err != nil {return err@@ -98,6 +103,37 @@ func NormalizeSRTFile(path string, allowOverlaps bool) error {return os.WriteFile(path, []byte(output.String()), 0644)}+// normalizeSRTBlockLayout repairs a common producer error where the subtitle+// text is written before the timestamp. The timestamp must still be a valid+// SRT timeline; malformed or missing timelines remain errors.+func normalizeSRTBlockLayout(block []string) ([]string, error) {+ if len(block) < 3 {+ return nil, fmt.Errorf("invalid SRT block")+ }+ timestampIndex := -1+ for index := 1; index < len(block); index++ {+ if srtTimelinePattern.MatchString(strings.TrimSpace(block[index])) {+ timestampIndex = index+ break+ }+ }+ if timestampIndex < 0 {+ return nil, fmt.Errorf("invalid SRT timestamp %q", strings.TrimSpace(block[1]))+ }+ if timestampIndex == 1 {+ return block, nil+ }++ normalized := make([]string, 0, len(block))+ normalized = append(normalized, block[0], block[timestampIndex])+ for index := 1; index < len(block); index++ {+ if index != timestampIndex {+ normalized = append(normalized, block[index])+ }+ }+ return normalized, nil+}+func parseSRTTimeline(value string) (int64, int64, error) {match := srtTimelinePattern.FindStringSubmatch(value)if match == nil {diff --git a/runtime/krillinai/internal/service/srt_timeline_test.go b/runtime/krillinai/internal/service/srt_timeline_test.goindex 479d8816..8f58f0f1 100644--- a/runtime/krillinai/internal/service/srt_timeline_test.go+++ b/runtime/krillinai/internal/service/srt_timeline_test.go@@ -60,6 +60,25 @@ func TestNormalizeSRTFileRepairsMergedTimelineAndPreservesText(t *testing.T) {}}+func TestNormalizeSRTFileRepairsTimestampWrittenAfterText(t *testing.T) {+ path := filepath.Join(t.TempDir(), "shifted.srt")+ content := "1\n[就像我们这样做。]\n00:00:01,000 --> 00:00:02,000\n\n"+ if err := os.WriteFile(path, []byte(content), 0644); err != nil {+ t.Fatal(err)+ }+ if err := NormalizeSRTFile(path, false); err != nil {+ t.Fatal(err)+ }+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ want := "1\n00:00:01,000 --> 00:00:02,000\n[就像我们这样做。]"+ if !strings.Contains(string(data), want) {+ t.Fatalf("timestamp/text order was not repaired: %q", string(data))+ }+}+type fixedTimestampMatcher struct{}func (fixedTimestampMatcher) GetLanguageType() types.StandardLanguageCode {