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 <haixin.yang@weimob.com>
This commit is contained in:
1 parent
86aef694ea
commit
eb3501b211
13 files changed
+183
-23
No files matched your search
+6
-4
@@ -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}
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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?.();
|
||||
})}><Waveform size={16} />{t("aiVoice")}</button>
|
||||
) : null}
|
||||
{contextMenu.track === "image" && builtInImageCaptionAvailable && contextImageSegment && contextImageSegment.type !== "video" ? (
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(() => generateImageCaption?.(contextImageSegment))}>
|
||||
<Sparkle size={16} />{t("generateImageAiCaption")}
|
||||
</button>
|
||||
) : null}
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(handleCutTrack)}><Scissors size={16} />{t("splitAtPlayhead")}</button>
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(handleDuplicateTrack)}><CopySimple size={16} />{t("duplicateClip")}</button>
|
||||
<div className="timeline-context-divider" />
|
||||
|
||||
@@ -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 配音");
|
||||
}}
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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 });
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 }));
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user