From eb3501b21184f5d5555d66175c6aa3bc0db9e00e Mon Sep 17 00:00:00 2001 From: Martin Delophy <845046459@qq.com> Date: Fri, 17 Jul 2026 19:14:43 +0800 Subject: [PATCH] Merge v0.3.4 voice reliability fixes (#19) * Add auto edit and polish timeline interactions * Release v0.3.3 * Release v0.3.4 --------- Co-authored-by: haixin.yang --- e2e/piper-languages.spec.js | 24 +++++++++---- package-lock.json | 4 +-- package.json | 2 +- public/model-cache-sw.js | 10 ++++++ src/App.jsx | 10 +++--- src/components/EditorSidebar.jsx | 2 ++ src/components/Timeline.jsx | 11 ++++++ src/components/panels.jsx | 4 +++ src/hooks/useAutoEdit.js | 33 +++++++++++++++--- src/hooks/useVoiceGeneration.js | 15 +++++++-- src/i18n.js | 7 ++++ src/lib/autoEdit.js | 26 ++++++++++++++ src/lib/piperVoiceRuntime.js | 58 +++++++++++++++++++++++++++++--- 13 files changed, 183 insertions(+), 23 deletions(-) diff --git a/e2e/piper-languages.spec.js b/e2e/piper-languages.spec.js index c927311..4c599ff 100644 --- a/e2e/piper-languages.spec.js +++ b/e2e/piper-languages.spec.js @@ -3,7 +3,9 @@ import { readFile } from "node:fs/promises"; const VOICE_CASES = [ { language: "中文", voice: "小雅", text: "你好,这是一次完整的中文语音合成测试。" }, + { language: "中文", voice: "超文", text: "你好,这是超文语音模型的合成测试。" }, { language: "English", voice: "Heart", text: "Hello. This is a complete English voice synthesis test." }, + { language: "English", voice: "Fenrir", text: "Hello. This is the second English voice synthesis test." }, { language: "Deutsch", voice: "Thorsten", text: "Hallo! Dies ist ein vollständiger Sprachtest." }, { language: "Español", voice: "DaveFX", text: "Hola. Esta es una prueba completa de síntesis de voz." }, { language: "Français", voice: "Siwis", text: "Bonjour. Ceci est un test complet de synthèse vocale." }, @@ -15,17 +17,27 @@ test.beforeEach(async ({ page }) => { await page.addInitScript(() => localStorage.setItem("ai-voiceover-ui-language", "zh")); }); -for (const voiceCase of VOICE_CASES) { - test(`${voiceCase.language} ${voiceCase.voice} generates a valid WAV through the editor`, async ({ page }) => { - await page.goto("/"); +test("every listed language and voice generates a valid WAV through the current editor workflow", async ({ page }) => { + test.setTimeout(20 * 60 * 1000); + await page.goto("/"); + + for (const voiceCase of VOICE_CASES) { + // Generation selects the newly created voice clip and switches the right + // panel to its clip inspector; explicitly return to the Audio workflow. + await page.locator(".rail-tool").filter({ hasText: "音频" }).click(); + await page.getByRole("button", { name: /AI 配音/ }).click(); + await expect(page.locator("#script-input")).toBeVisible(); await page.locator("#script-input").fill(voiceCase.text); await page.locator(".voice-filter").click(); await page.locator(".menu-list button").getByText(voiceCase.language, { exact: true }).click(); + await page.locator(".voice-card").filter({ hasText: voiceCase.voice }).click(); await expect(page.locator(".voice-card.is-selected strong")).toHaveText(voiceCase.voice); + const previousClipCount = await page.locator(".audio-clip:not(.is-source)").count(); await page.locator(".generate-button").click(); + await expect(page.locator(".audio-clip:not(.is-source)")).toHaveCount(previousClipCount + 1, { timeout: 4 * 60 * 1000 }); const clipDownload = page.getByRole("button", { name: "下载片段", exact: true }); - await expect(clipDownload).toBeEnabled({ timeout: 4 * 60 * 1000 }); + await expect(clipDownload).toBeEnabled(); const downloadPromise = page.waitForEvent("download"); await clipDownload.click(); @@ -36,5 +48,5 @@ for (const voiceCase of VOICE_CASES) { expect(wav.byteLength).toBeGreaterThan(44); expect(wav.subarray(0, 4).toString("ascii")).toBe("RIFF"); expect(wav.subarray(8, 12).toString("ascii")).toBe("WAVE"); - }); -} + } +}); diff --git a/package-lock.json b/package-lock.json index 32e2586..e37c1bf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "web-player", - "version": "0.3.3", + "version": "0.3.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "web-player", - "version": "0.3.3", + "version": "0.3.4", "license": "MIT", "dependencies": { "@diffusionstudio/vits-web": "^1.0.3", diff --git a/package.json b/package.json index a228862..a0fdafd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "web-player", - "version": "0.3.3", + "version": "0.3.4", "private": true, "description": "A local-first browser AI video editor for voiceovers, captions, talking avatars, and multi-track timeline export.", "license": "MIT", diff --git a/public/model-cache-sw.js b/public/model-cache-sw.js index 903bf29..f050ce7 100644 --- a/public/model-cache-sw.js +++ b/public/model-cache-sw.js @@ -36,9 +36,18 @@ function isHuggingFaceModelRequest(url) { return false; } + // Piper's runtime owns its OPFS cache. Caching the same voice files here + // would keep a second full model copy for every non-English language. + if (url.pathname.includes("/rhasspy/piper-voices/resolve/")) return false; return url.hostname !== "huggingface.co" || url.pathname.includes("/resolve/"); } +async function removeLegacyPiperDuplicates() { + const cache = await caches.open(MODEL_CACHE_NAME); + const keys = await cache.keys(); + await Promise.all(keys.filter((request) => new URL(request.url).pathname.includes("/rhasspy/piper-voices/resolve/")).map((request) => cache.delete(request))); +} + function isRuntimeAssetRequest(url) { if (url.origin === self.location.origin) { return url.pathname.startsWith("/models/") @@ -119,6 +128,7 @@ self.addEventListener("activate", (event) => { // Older Transformers.js builds created a second copy of Hugging Face model // assets here. The service worker is now the sole cache owner. event.waitUntil(caches.delete("transformers-cache").catch(() => false)); + event.waitUntil(removeLegacyPiperDuplicates().catch(() => {})); }); self.addEventListener("fetch", (event) => { diff --git a/src/App.jsx b/src/App.jsx index b0637b7..a66b08c 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -340,8 +340,8 @@ export function App() { setVisionRecords, trackLocks, }); const autoEdit = useAutoEdit({ - language: activeLanguage, visualSegments, commitCaptionSegments, setCaptionsEnabled, - setSelectedSegmentId, setSelectedTrack, notify, t, + language: activeLanguage, visualSegments, captionSegments, commitCaptionSegments, setCaptionsEnabled, + setTrackVisibility, setSelectedSegmentId, setSelectedTrack, notify, t, }); const { clearAudioTrack, clearMusicTrack, clearSourceAudioTrack, commitAudio, @@ -703,8 +703,8 @@ export function App() { seekTo, segments, selectTool, selectedCaptionSegment, selectedFilterId, selectedLibraryAssetId, selectedSegmentId, selectedStickerId, selectedTransitionId, selectedVoice, setCaptionSize, setCaptionStyle, setCaptionsEnabled, setIsDragging, - setMediaTab, setMusicVolume, setSelectedFilterId, setSelectedSegmentId, - setSelectedStickerId, setSelectedTransitionId, setSourceAudioVolume, setVoiceTab, + setMediaTab, setMusicVolume, setSelectedAudioSegmentId, setSelectedFilterId, setSelectedSegmentId, + setSelectedStickerId, setSelectedTrack, setSelectedTransitionId, setSourceAudioVolume, setVoiceTab, sourceAudioBlob, sourceAudioDuration, sourceAudioLinked, sourceAudioName, sourceAudioVolume, status, t, separateSourceVocals, vocalSeparationJob, toggleCaptionSegmentHidden, toggleVisionOption, trOption, updateCaptionSegmentText, @@ -927,6 +927,8 @@ export function App() { currentVisualSegment={currentVisualSegment} selectedVisualSegmentId={selectedVisualSegmentId} currentVisualSegmentIndex={currentVisualSegmentIndex} + builtInImageCaptionAvailable={autoEdit.support.availability === "available"} + generateImageCaption={autoEdit.generateImageCaption} setSelectedVisualSegmentId={setSelectedVisualSegmentId} seekTo={seekTo} suppressTimelineClipClickRef={suppressTimelineClipClickRef} diff --git a/src/components/EditorSidebar.jsx b/src/components/EditorSidebar.jsx index f7f5fc9..7763a02 100644 --- a/src/components/EditorSidebar.jsx +++ b/src/components/EditorSidebar.jsx @@ -50,6 +50,8 @@ export function EditorSidebar({ model: d }) { selectedCaptionSegment={d.selectedCaptionSegment} selectedSegmentId={d.selectedSegmentId} setSelectedSegmentId={d.setSelectedSegmentId} + setSelectedAudioSegmentId={d.setSelectedAudioSegmentId} + setSelectedTrack={d.setSelectedTrack} updateCaptionSegmentText={d.updateCaptionSegmentText} toggleCaptionSegmentHidden={d.toggleCaptionSegmentHidden} deleteCaptionSegment={d.deleteCaptionSegment} diff --git a/src/components/Timeline.jsx b/src/components/Timeline.jsx index a5b39a4..5a319af 100644 --- a/src/components/Timeline.jsx +++ b/src/components/Timeline.jsx @@ -20,6 +20,7 @@ import { Play, PlusCircle, Scissors, + Sparkle, SlidersHorizontal, Trash, Waveform, @@ -170,6 +171,8 @@ export function Timeline({ currentVisualSegment, selectedVisualSegmentId, currentVisualSegmentIndex, + builtInImageCaptionAvailable = false, + generateImageCaption, setSelectedVisualSegmentId, seekTo, suppressTimelineClipClickRef, @@ -267,6 +270,9 @@ export function Timeline({ contentWidth: 0, }); const [contextMenu, setContextMenu] = useState(null); + const contextImageSegment = contextMenu?.track === "image" && contextMenu.segmentId + ? displayedVisualSegments.find((segment) => segment.id === contextMenu.segmentId) + : null; const trackTool = (track) => ({ image: "media", sticker: "stickers", caption: "caption", source: "audio", audio: "audio", music: "audio" })[track] || "media"; const openTrackPanel = (track) => { setSelectedTrack(track); @@ -1244,6 +1250,11 @@ export function Timeline({ requestCaptionVoiceFocus?.(); })}>{t("aiVoice")} ) : null} + {contextMenu.track === "image" && builtInImageCaptionAvailable && contextImageSegment && contextImageSegment.type !== "video" ? ( + + ) : null}
diff --git a/src/components/panels.jsx b/src/components/panels.jsx index 83250f5..16d928b 100644 --- a/src/components/panels.jsx +++ b/src/components/panels.jsx @@ -223,6 +223,8 @@ export function ToolPanel(props) { selectedCaptionSegment, selectedSegmentId, setSelectedSegmentId, + setSelectedAudioSegmentId, + setSelectedTrack, updateCaptionSegmentText, toggleCaptionSegmentHidden, deleteCaptionSegment, @@ -375,6 +377,8 @@ export function ToolPanel(props) { className="audio-entry-card" type="button" onClick={() => { + setSelectedAudioSegmentId?.(""); + setSelectedTrack?.(""); setVoiceTab("synthesis"); notify("已打开 AI 配音"); }} diff --git a/src/hooks/useAutoEdit.js b/src/hooks/useAutoEdit.js index 3c73f4d..7b765df 100644 --- a/src/hooks/useAutoEdit.js +++ b/src/hooks/useAutoEdit.js @@ -1,8 +1,8 @@ import { useCallback, useEffect, useRef, useState } from "react"; -import { createFrameCaptionSession, extractAutoEditFrames, generateFrameCaptions, probeBuiltInAI } from "../lib/autoEdit.js"; -import { getVisualSegmentsTotal } from "../lib/timeline.js"; +import { createFrameCaptionSession, extractAutoEditFrames, generateFrameCaptions, generateImageVoiceoverText, probeBuiltInAI } from "../lib/autoEdit.js"; +import { getVisualSegmentsTotal, makeId } from "../lib/timeline.js"; -export function useAutoEdit({ language, visualSegments, commitCaptionSegments, setCaptionsEnabled, setSelectedSegmentId, setSelectedTrack, notify, t }) { +export function useAutoEdit({ language, visualSegments, captionSegments, commitCaptionSegments, setCaptionsEnabled, setTrackVisibility, setSelectedSegmentId, setSelectedTrack, notify, t }) { const [support, setSupport] = useState({ availability: "unknown", reason: "", language: "en" }); const [job, setJob] = useState({ running: false, progress: 0, phase: "" }); const [review, setReview] = useState({ open: false, candidates: [], captions: [], segments: [], error: "" }); @@ -19,6 +19,31 @@ export function useAutoEdit({ language, visualSegments, commitCaptionSegments, s setSupport(result); return result; }, [language]); + useEffect(() => { checkSupport(); }, [checkSupport]); + + const generateImageCaption = useCallback(async (segment) => { + if (!segment?.src || segment.type === "video" || support.availability !== "available" || job.running) return; + const index = visualSegments.findIndex((item) => item.id === segment.id); + if (index < 0) return; + const start = visualSegments.slice(0, index).reduce((sum, item) => sum + Math.max(0, Number(item.duration) || 0), 0); + const end = start + Math.max(0.2, Number(segment.duration) || 0.2); + setJob({ running: true, progress: 15, phase: t("autoEditWritingCaptions") }); + try { + const text = await generateImageVoiceoverText({ src: segment.src, language }); + const caption = { id: makeId("caption"), text, start, end, hidden: false, visualSegmentId: segment.id }; + const next = [...captionSegments, caption].sort((a, b) => (Number(a.start) || 0) - (Number(b.start) || 0)); + commitCaptionSegments(next, t("imageAiCaptionAdded"), next.findIndex((item) => item.id === caption.id)); + setCaptionsEnabled(true); + setTrackVisibility((visibility) => ({ ...visibility, caption: true })); + setSelectedTrack("caption"); setSelectedSegmentId(caption.id); + notify(t("imageAiCaptionAdded")); + } catch (error) { + console.error(error); + notify(t("imageAiCaptionFailed")); + } finally { + setJob({ running: false, progress: 0, phase: "" }); + } + }, [captionSegments, commitCaptionSegments, job.running, language, notify, setCaptionsEnabled, setSelectedSegmentId, setSelectedTrack, setTrackVisibility, support.availability, t, visualSegments]); const run = useCallback(async () => { if (!visualSegments.length || job.running) return; const environment = support.availability === "unknown" ? await checkSupport() : support; @@ -85,5 +110,5 @@ export function useAutoEdit({ language, visualSegments, commitCaptionSegments, s notify(t("autoEditDone")); closeReview(); }; - return { support, job, review, checkSupport, run, cancel, closeReview, applyCaptions }; + return { support, job, review, checkSupport, run, generateImageCaption, cancel, closeReview, applyCaptions }; } diff --git a/src/hooks/useVoiceGeneration.js b/src/hooks/useVoiceGeneration.js index 3db64a7..c36ffbe 100644 --- a/src/hooks/useVoiceGeneration.js +++ b/src/hooks/useVoiceGeneration.js @@ -39,10 +39,21 @@ export function useVoiceGeneration(d) { d.setStatusText(d.t("ttsStatusClearingCache")); await tts.flush?.(); blob = await predictPiperVoice(tts, input, progress); } } else { - const { KokoroTTS } = await import("kokoro-js"); d.setStatusText(d.t("ttsStatusLoadingKokoro")); + // Kokoro and the editor share the same Transformers runtime. Disable + // its second Cache Storage layer before Kokoro starts loading; the + // project service worker already owns persistent model caching. + const [{ env: transformersEnv }, { KokoroTTS }] = await Promise.all([ + import("@huggingface/transformers"), + import("kokoro-js"), + ]); + transformersEnv.useBrowserCache = false; + d.setStatusText(d.t("ttsStatusLoadingKokoro")); const progressCallback = (event) => { if (event?.progress) d.setProgress((current) => Math.max(current, Math.min(86, Math.max(10, Math.round(event.progress))))); }; let tts; - if (globalThis.navigator?.gpu) { + const webGpuAdapter = globalThis.navigator?.gpu + ? await globalThis.navigator.gpu.requestAdapter().catch(() => null) + : null; + if (webGpuAdapter) { try { d.setStatusText(d.t("ttsStatusLoadingWebGpu")); tts = await KokoroTTS.from_pretrained(MODEL_ID, { dtype: "fp32", device: "webgpu", progress_callback: progressCallback }); diff --git a/src/i18n.js b/src/i18n.js index f6733ac..2264d6b 100644 --- a/src/i18n.js +++ b/src/i18n.js @@ -294,6 +294,11 @@ const AUTO_EDIT_RESULT_COPY = { en: { autoEditNoResults: "All clips were processed, but no usable captions were generated" }, }; +const IMAGE_AI_CAPTION_COPY = { + zh: { generateImageAiCaption: "AI 生成口播字幕", imageAiCaptionAdded: "AI 口播字幕已加入时间线", imageAiCaptionFailed: "无法生成图片口播字幕" }, + en: { generateImageAiCaption: "Generate AI voiceover caption", imageAiCaptionAdded: "AI voiceover caption added to the timeline", imageAiCaptionFailed: "Could not generate an image voiceover caption" }, +}; + export const UI_COPY = { zh: { ...SMART_WORKSPACE_COPY.zh, @@ -303,6 +308,7 @@ export const UI_COPY = { ...AUTO_EDIT_FLOW_COPY.zh, ...AUTO_EDIT_SEGMENT_COPY.zh, ...AUTO_EDIT_RESULT_COPY.zh, + ...IMAGE_AI_CAPTION_COPY.zh, ...VISUAL_EDITOR_COPY.zh, ...TRANSITION_EDITOR_COPY.zh, ...VISUAL_ANIMATION_COPY.zh, @@ -682,6 +688,7 @@ export const UI_COPY = { ...AUTO_EDIT_FLOW_COPY.en, ...AUTO_EDIT_SEGMENT_COPY.en, ...AUTO_EDIT_RESULT_COPY.en, + ...IMAGE_AI_CAPTION_COPY.en, ...VISUAL_EDITOR_COPY.en, ...TRANSITION_EDITOR_COPY.en, ...VISUAL_ANIMATION_COPY.en, diff --git a/src/lib/autoEdit.js b/src/lib/autoEdit.js index d24e53b..a0449a1 100644 --- a/src/lib/autoEdit.js +++ b/src/lib/autoEdit.js @@ -233,6 +233,32 @@ export function createFrameCaptionSession({ language, onDownloadProgress, signal return window.LanguageModel.create(options); } +export async function generateImageVoiceoverText({ src, language = "en", signal }) { + if (!src) throw new Error("image-missing"); + const modelLanguage = getAutoEditLanguage(language); + const session = await createFrameCaptionSession({ language, signal }); + try { + const response = await fetch(src, { signal }); + if (!response.ok) throw new Error("image-load-failed"); + const image = await response.blob(); + const schema = { + type: "object", + properties: { text: { type: "string", minLength: 1 } }, + required: ["text"], + additionalProperties: false, + }; + const result = await session.prompt([{ role: "user", content: [ + { type: "text", value: `Write one concise, natural voiceover narration sentence in ${modelLanguage} describing only the visible content of this image. Do not invent names, identities, locations, or unseen events. Do not use labels, markdown, or quotation marks.` }, + { type: "image", value: image }, + ] }], { responseConstraint: schema, signal }); + const text = String(JSON.parse(result)?.text || "").trim(); + if (!text) throw new Error("empty-caption"); + return text; + } finally { + session.destroy?.(); + } +} + async function generateCaptionGroup(session, frames, duration, modelLanguage) { const content = [{ type: "text", value: `Describe every provided candidate frame with one concise on-screen caption. Output in ${modelLanguage}. Return exactly ${frames.length} captions in the same order as the images. Use only visible evidence; do not invent names or facts. Frame timestamps: ${frames.map((frame) => frame.time.toFixed(2)).join(", ")} seconds.` }]; frames.forEach((frame) => content.push({ type: "image", value: frame.blob })); diff --git a/src/lib/piperVoiceRuntime.js b/src/lib/piperVoiceRuntime.js index ce094e3..93d8cf0 100644 --- a/src/lib/piperVoiceRuntime.js +++ b/src/lib/piperVoiceRuntime.js @@ -19,6 +19,37 @@ const DIGITS = { 0: "零", 1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: const pinyinRuntimePromises = new Map(); +async function getPinyinCacheFile(fileName, create = false) { + if (!globalThis.navigator?.storage?.getDirectory) return null; + const root = await navigator.storage.getDirectory(); + const piper = await root.getDirectoryHandle("piper", { create }); + const pinyinVoices = await piper.getDirectoryHandle("pinyin-voices", { create }); + return pinyinVoices.getFileHandle(fileName, { create }); +} + +async function readPinyinCache(fileName) { + try { + const handle = await getPinyinCacheFile(fileName); + return handle ? (await handle.getFile()).arrayBuffer() : null; + } catch { + return null; + } +} + +async function writePinyinCache(fileName, data) { + try { + const handle = await getPinyinCacheFile(fileName, true); + if (!handle) return; + const writable = await handle.createWritable(); + await writable.write(data); + await writable.close(); + } catch (error) { + // Persistence is optional. Keep the downloaded bytes available to the + // current inference even when the browser quota is full. + console.warn("Piper OPFS cache write skipped.", error); + } +} + function normalizeNumbers(text) { return text.replace(/\d/g, (digit) => DIGITS[digit]); } @@ -70,10 +101,20 @@ function encodeWav(samples, sampleRate) { } async function fetchArrayBufferWithProgress(url, onProgress, voiceName) { + const cacheName = `${voiceName}-${url.split("/").at(-1)}`; + const cached = await readPinyinCache(cacheName); + if (cached) { + onProgress?.({ url, total: cached.byteLength, loaded: cached.byteLength, cached: true }); + return cached; + } const response = await fetch(url); if (!response.ok) throw new Error(`${voiceName}模型下载失败 (${response.status})`); const total = Number(response.headers.get("content-length")) || 0; - if (!response.body) return response.arrayBuffer(); + if (!response.body) { + const data = await response.arrayBuffer(); + await writePinyinCache(cacheName, data); + return data; + } const reader = response.body.getReader(); const chunks = []; let loaded = 0; @@ -86,6 +127,7 @@ async function fetchArrayBufferWithProgress(url, onProgress, voiceName) { const bytes = new Uint8Array(loaded); let offset = 0; for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } + await writePinyinCache(cacheName, bytes); return bytes.buffer; } @@ -93,9 +135,17 @@ async function loadPinyinVoice(voiceId, onProgress) { const voicePath = PINYIN_VOICES[voiceId]; const voiceName = voiceId === "zh_CN-xiao_ya-medium" ? "小雅" : "超文"; const voiceBase = `${PIPER_BASE}/${voicePath}`; - const configResponse = await fetch(`${voiceBase}/${voiceId}.onnx.json`); - if (!configResponse.ok) throw new Error(`${voiceName}配置下载失败 (${configResponse.status})`); - const config = await configResponse.json(); + const configUrl = `${voiceBase}/${voiceId}.onnx.json`; + const cachedConfig = await readPinyinCache(`${voiceName}-${voiceId}.onnx.json`); + let config; + if (cachedConfig) config = JSON.parse(new TextDecoder().decode(cachedConfig)); + else { + const configResponse = await fetch(configUrl); + if (!configResponse.ok) throw new Error(`${voiceName}配置下载失败 (${configResponse.status})`); + const configBytes = await configResponse.arrayBuffer(); + config = JSON.parse(new TextDecoder().decode(configBytes)); + await writePinyinCache(`${voiceName}-${voiceId}.onnx.json`, configBytes); + } const model = await fetchArrayBufferWithProgress(`${voiceBase}/${voiceId}.onnx`, onProgress, voiceName); if (globalThis.navigator?.gpu) { try {