Add sticker timeline and offline model caching
This commit is contained in:
1 parent
ddb6f4a5e1
commit
1cc16c8c2f
65 files changed
+4432
-373
No files matched your search
+797
@@ -0,0 +1,797 @@
|
||||
import { AUTOMATIC_CAPTION_MODEL_ID, AUTOMATIC_CAPTION_MODEL_LABEL } from "../config/models.js";
|
||||
import { makeId } from "./timeline.js";
|
||||
|
||||
const ASR_SAMPLE_RATE = 16000;
|
||||
const MIN_CAPTION_DURATION = 0.45;
|
||||
const FALLBACK_CAPTION_SECONDS = 3.2;
|
||||
const LANGUAGE_DETECTION_SECONDS = 20;
|
||||
const CHINESE_VISIBLE_CHAR_THRESHOLD = 8;
|
||||
const ENERGY_FRAME_SECONDS = 0.05;
|
||||
const ENERGY_MERGE_GAP_SECONDS = 0.35;
|
||||
const ENERGY_MIN_INTERVAL_SECONDS = 0.1;
|
||||
const ENERGY_SEQUENCE_MIN_INTERVAL_SECONDS = 0.48;
|
||||
const ENERGY_SEQUENCE_REALIGN_LEAD_SECONDS = 1;
|
||||
const ENERGY_SEQUENCE_FIRST_START_SECONDS = 0.75;
|
||||
const ENERGY_SKIPPED_INTERVAL_RATIO = 0.95;
|
||||
const ENERGY_BOUNDARY_PADDING_SECONDS = 0.12;
|
||||
const ENERGY_MAX_EXTENSION_SECONDS = 0.45;
|
||||
const CHINESE_CAPTION_CHARS_PER_SECOND = 5;
|
||||
const MAX_SEQUENCE_CAPTION_SECONDS = 4.5;
|
||||
const CJK_PATTERN = /[\u3400-\u9fff]/;
|
||||
|
||||
const CHINESE_ASR_CONTEXT_REPLACEMENTS = [
|
||||
[/侯[父付负](?=主[母姆幕]|夫人|公子|小姐|世子|嫡|庶|门|中|里|内|上下)/g, "侯府"],
|
||||
[/候府(?=主[母姆幕]|夫人|公子|小姐|世子|嫡|庶|门|中|里|内|上下)/g, "侯府"],
|
||||
[/(侯府)主[姆幕](?=$|[,。!?!?、\s])/g, "$1主母"],
|
||||
];
|
||||
|
||||
const UI_LANGUAGE_TO_WHISPER_LANGUAGE = {
|
||||
zh: "zh",
|
||||
en: "en",
|
||||
ja: "ja",
|
||||
ko: "ko",
|
||||
es: "es",
|
||||
fr: "fr",
|
||||
de: "de",
|
||||
pt: "pt",
|
||||
th: "th",
|
||||
vi: "vi",
|
||||
};
|
||||
|
||||
const WHISPER_LANGUAGE_NAMES = {
|
||||
zh: "中文",
|
||||
en: "English",
|
||||
ja: "日本語",
|
||||
ko: "한국어",
|
||||
es: "Español",
|
||||
fr: "Français",
|
||||
de: "Deutsch",
|
||||
pt: "Português",
|
||||
th: "ไทย",
|
||||
vi: "Tiếng Việt",
|
||||
};
|
||||
|
||||
let transcriberState = null;
|
||||
let asrWorker = null;
|
||||
let shouldSkipAsrWorker = false;
|
||||
const workerRequests = new Map();
|
||||
|
||||
function getAudioContext(sampleRate = ASR_SAMPLE_RATE) {
|
||||
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
|
||||
if (!AudioContextClass) {
|
||||
throw new Error("当前浏览器不支持 AudioContext,无法识别音频。");
|
||||
}
|
||||
|
||||
return new AudioContextClass({ sampleRate });
|
||||
}
|
||||
|
||||
function downmixToMono(decoded) {
|
||||
if (decoded.numberOfChannels <= 1) {
|
||||
return new Float32Array(decoded.getChannelData(0));
|
||||
}
|
||||
|
||||
const left = decoded.getChannelData(0);
|
||||
const right = decoded.getChannelData(1);
|
||||
const mono = new Float32Array(decoded.length);
|
||||
const scale = Math.SQRT2 / 2;
|
||||
for (let index = 0; index < decoded.length; index += 1) {
|
||||
mono[index] = (left[index] + right[index]) * scale;
|
||||
}
|
||||
return mono;
|
||||
}
|
||||
|
||||
async function decodeAudioForAsr(blob) {
|
||||
const audioContext = getAudioContext();
|
||||
try {
|
||||
const buffer = await blob.arrayBuffer();
|
||||
const decoded = await audioContext.decodeAudioData(buffer.slice(0));
|
||||
return {
|
||||
audio: downmixToMono(decoded),
|
||||
duration: decoded.duration,
|
||||
};
|
||||
} finally {
|
||||
await audioContext.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTimestampValue(value) {
|
||||
if (value === null || value === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized = Number(value);
|
||||
return Number.isFinite(normalized) ? normalized : null;
|
||||
}
|
||||
|
||||
function normalizeTimestamp(timestamp, fallbackStart, fallbackEnd, timelineOffset = 0) {
|
||||
if (!Array.isArray(timestamp)) {
|
||||
return [fallbackStart + timelineOffset, fallbackEnd + timelineOffset];
|
||||
}
|
||||
|
||||
const [rawStart, rawEnd] = timestamp;
|
||||
const timestampStart = normalizeTimestampValue(rawStart);
|
||||
const timestampEnd = normalizeTimestampValue(rawEnd);
|
||||
const start = (timestampStart ?? fallbackStart) + timelineOffset;
|
||||
const end = (timestampEnd ?? fallbackEnd) + timelineOffset;
|
||||
return [Math.max(0, start), Math.max(start + MIN_CAPTION_DURATION, end)];
|
||||
}
|
||||
|
||||
function normalizeAsrWhitespace(text, language) {
|
||||
const normalized = String(text ?? "").replace(/\s+/g, " ").trim();
|
||||
if (language !== "zh") {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
return normalized.replace(/([\u3400-\u9fff])\s+([\u3400-\u9fff])/g, "$1$2");
|
||||
}
|
||||
|
||||
function normalizeChineseAsrText(text) {
|
||||
if (!CJK_PATTERN.test(text)) {
|
||||
return text;
|
||||
}
|
||||
|
||||
return CHINESE_ASR_CONTEXT_REPLACEMENTS.reduce(
|
||||
(currentText, [pattern, replacement]) => currentText.replace(pattern, replacement),
|
||||
text,
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeAsrText(text, language) {
|
||||
const normalized = normalizeAsrWhitespace(text, language);
|
||||
return language === "zh" ? normalizeChineseAsrText(normalized) : normalized;
|
||||
}
|
||||
|
||||
function outputToCaptionSegments(output, duration, timelineOffset = 0, language = "zh") {
|
||||
const chunks = Array.isArray(output?.chunks) ? output.chunks : [];
|
||||
let previousEnd = timelineOffset;
|
||||
const segments = chunks
|
||||
.map((chunk, index) => {
|
||||
const rawText = normalizeAsrWhitespace(chunk.text, language);
|
||||
const text = normalizeAsrText(rawText, language);
|
||||
if (!text) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const fallbackStart = Math.max(
|
||||
0,
|
||||
Math.min(duration, index === 0 ? 0 : previousEnd - timelineOffset),
|
||||
);
|
||||
const fallbackEnd = Math.min(duration, fallbackStart + FALLBACK_CAPTION_SECONDS);
|
||||
const [start, end] = normalizeTimestamp(
|
||||
chunk.timestamp,
|
||||
fallbackStart,
|
||||
fallbackEnd,
|
||||
timelineOffset,
|
||||
);
|
||||
const clampedStart = Math.min(
|
||||
duration + timelineOffset,
|
||||
Math.max(timelineOffset, start < previousEnd - 0.05 ? previousEnd : start),
|
||||
);
|
||||
const clampedEnd = Math.min(
|
||||
duration + timelineOffset,
|
||||
Math.max(clampedStart + MIN_CAPTION_DURATION, end),
|
||||
);
|
||||
previousEnd = clampedEnd;
|
||||
|
||||
return {
|
||||
id: makeId("caption"),
|
||||
text,
|
||||
rawText: rawText !== text ? rawText : undefined,
|
||||
start: clampedStart,
|
||||
end: clampedEnd,
|
||||
hidden: false,
|
||||
source: "asr",
|
||||
};
|
||||
})
|
||||
.filter(Boolean)
|
||||
.filter((segment) => segment.end > segment.start)
|
||||
.sort((a, b) => a.start - b.start);
|
||||
|
||||
if (segments.length) {
|
||||
return segments;
|
||||
}
|
||||
|
||||
const rawText = normalizeAsrWhitespace(output?.text, language);
|
||||
const text = normalizeAsrText(rawText, language);
|
||||
return text
|
||||
? [
|
||||
{
|
||||
id: makeId("caption"),
|
||||
text,
|
||||
rawText: rawText !== text ? rawText : undefined,
|
||||
start: timelineOffset,
|
||||
end: timelineOffset + Math.max(MIN_CAPTION_DURATION, duration || FALLBACK_CAPTION_SECONDS),
|
||||
hidden: false,
|
||||
source: "asr",
|
||||
},
|
||||
]
|
||||
: [];
|
||||
}
|
||||
|
||||
function getQuantile(sortedValues, quantile) {
|
||||
if (!sortedValues.length) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const index = Math.max(0, Math.min(sortedValues.length - 1, Math.floor(sortedValues.length * quantile)));
|
||||
return sortedValues[index];
|
||||
}
|
||||
|
||||
function getAudioEnergyFrames(audio) {
|
||||
const frameLength = Math.max(1, Math.round(ASR_SAMPLE_RATE * ENERGY_FRAME_SECONDS));
|
||||
const frames = [];
|
||||
for (let index = 0; index < audio.length; index += frameLength) {
|
||||
let sum = 0;
|
||||
const end = Math.min(audio.length, index + frameLength);
|
||||
for (let sampleIndex = index; sampleIndex < end; sampleIndex += 1) {
|
||||
sum += audio[sampleIndex] * audio[sampleIndex];
|
||||
}
|
||||
|
||||
frames.push({
|
||||
start: index / ASR_SAMPLE_RATE,
|
||||
end: end / ASR_SAMPLE_RATE,
|
||||
rms: Math.sqrt(sum / Math.max(1, end - index)),
|
||||
});
|
||||
}
|
||||
return frames;
|
||||
}
|
||||
|
||||
function getActiveAudioIntervals(audio) {
|
||||
const frames = getAudioEnergyFrames(audio);
|
||||
if (!frames.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rmsValues = frames.map((frame) => frame.rms).sort((a, b) => a - b);
|
||||
const median = getQuantile(rmsValues, 0.5);
|
||||
const upperMid = getQuantile(rmsValues, 0.75);
|
||||
const loud = getQuantile(rmsValues, 0.9);
|
||||
const threshold = Math.max(0.008, median * 1.8, upperMid * 1.12, loud * 0.45);
|
||||
const rawIntervals = [];
|
||||
let currentStart = null;
|
||||
let currentEnd = null;
|
||||
|
||||
frames.forEach((frame) => {
|
||||
if (frame.rms >= threshold) {
|
||||
currentStart ??= frame.start;
|
||||
currentEnd = frame.end;
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentStart !== null && currentEnd - currentStart >= ENERGY_MIN_INTERVAL_SECONDS) {
|
||||
rawIntervals.push({ start: currentStart, end: currentEnd });
|
||||
}
|
||||
currentStart = null;
|
||||
currentEnd = null;
|
||||
});
|
||||
|
||||
if (currentStart !== null && currentEnd - currentStart >= ENERGY_MIN_INTERVAL_SECONDS) {
|
||||
rawIntervals.push({ start: currentStart, end: currentEnd });
|
||||
}
|
||||
|
||||
return rawIntervals.reduce((merged, interval) => {
|
||||
const previous = merged.at(-1);
|
||||
if (previous && interval.start - previous.end <= ENERGY_MERGE_GAP_SECONDS) {
|
||||
previous.end = Math.max(previous.end, interval.end);
|
||||
return merged;
|
||||
}
|
||||
|
||||
merged.push({ ...interval });
|
||||
return merged;
|
||||
}, []);
|
||||
}
|
||||
|
||||
function scoreActiveInterval(interval, segmentStart, segmentEnd) {
|
||||
const duration = interval.end - interval.start;
|
||||
const endDistance = Math.abs(interval.end - segmentEnd);
|
||||
const centerDistance = Math.abs((interval.start + interval.end - segmentStart - segmentEnd) / 2);
|
||||
return duration * 1.8 - endDistance * 0.35 - centerDistance * 0.05;
|
||||
}
|
||||
|
||||
function findBestActiveInterval(intervals, searchStart, searchEnd, segmentStart, segmentEnd) {
|
||||
return intervals
|
||||
.map((interval) => ({
|
||||
start: Math.max(searchStart, interval.start),
|
||||
end: Math.min(searchEnd, interval.end),
|
||||
}))
|
||||
.filter((interval) => interval.end - interval.start >= ENERGY_MIN_INTERVAL_SECONDS)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
scoreActiveInterval(right, segmentStart, segmentEnd) -
|
||||
scoreActiveInterval(left, segmentStart, segmentEnd),
|
||||
)[0] ?? null;
|
||||
}
|
||||
|
||||
function getIntervalDuration(interval) {
|
||||
return Math.max(0, interval.end - interval.start);
|
||||
}
|
||||
|
||||
function getRealignedEnergySequence(intervals, segments, timelineOffset = 0) {
|
||||
if (segments.length < 2 || intervals.length <= segments.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const firstSegmentStart = Math.max(0, segments[0].start - timelineOffset);
|
||||
if (firstSegmentStart > ENERGY_SEQUENCE_FIRST_START_SECONDS) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const meaningfulIntervals = intervals.filter(
|
||||
(interval) => getIntervalDuration(interval) >= ENERGY_SEQUENCE_MIN_INTERVAL_SECONDS,
|
||||
);
|
||||
if (meaningfulIntervals.length <= segments.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const candidateIntervals = meaningfulIntervals.slice(-segments.length);
|
||||
const skippedIntervals = meaningfulIntervals.slice(0, -segments.length);
|
||||
const firstCandidateDuration = getIntervalDuration(candidateIntervals[0]);
|
||||
const skippedMaxDuration = skippedIntervals.reduce(
|
||||
(maxDuration, interval) => Math.max(maxDuration, getIntervalDuration(interval)),
|
||||
0,
|
||||
);
|
||||
const hasClearLeadIn = candidateIntervals[0].start - firstSegmentStart >= ENERGY_SEQUENCE_REALIGN_LEAD_SECONDS;
|
||||
const skippedLooksLikeNoise = skippedMaxDuration <= firstCandidateDuration * ENERGY_SKIPPED_INTERVAL_RATIO;
|
||||
|
||||
return hasClearLeadIn && skippedLooksLikeNoise ? candidateIntervals : null;
|
||||
}
|
||||
|
||||
function getEstimatedCaptionSpeechSeconds(text) {
|
||||
const compactText = String(text ?? "").replace(/\s/g, "");
|
||||
const cjkCount = compactText.match(/[\u3400-\u9fff]/g)?.length ?? 0;
|
||||
if (cjkCount) {
|
||||
return Math.max(
|
||||
MIN_CAPTION_DURATION,
|
||||
Math.min(MAX_SEQUENCE_CAPTION_SECONDS, cjkCount / CHINESE_CAPTION_CHARS_PER_SECOND + 0.6),
|
||||
);
|
||||
}
|
||||
|
||||
const wordCount = compactText ? Math.max(1, compactText.split(/\s+/).length) : 1;
|
||||
return Math.max(MIN_CAPTION_DURATION, Math.min(MAX_SEQUENCE_CAPTION_SECONDS, wordCount / 2.8 + 0.8));
|
||||
}
|
||||
|
||||
function refineCaptionSegmentsWithAudioEnergy(segments, audio, duration, timelineOffset = 0) {
|
||||
if (!segments.length || !audio.length || duration <= 0) {
|
||||
return segments;
|
||||
}
|
||||
|
||||
const intervals = getActiveAudioIntervals(audio);
|
||||
if (!intervals.length) {
|
||||
return segments;
|
||||
}
|
||||
|
||||
let previousEnd = timelineOffset;
|
||||
const realignedSequence = getRealignedEnergySequence(intervals, segments, timelineOffset);
|
||||
return segments.map((segment, index) => {
|
||||
const localStart = Math.max(0, segment.start - timelineOffset);
|
||||
const localEnd = Math.max(localStart + MIN_CAPTION_DURATION, segment.end - timelineOffset);
|
||||
const hasNextSegment = Number.isFinite(segments[index + 1]?.start);
|
||||
const nextLocalStart = hasNextSegment
|
||||
? Math.max(0, segments[index + 1].start - timelineOffset)
|
||||
: duration;
|
||||
const searchStart = Math.max(0, localStart - 0.35);
|
||||
const searchEnd = Math.min(
|
||||
duration,
|
||||
hasNextSegment ? nextLocalStart - 0.05 : duration,
|
||||
localEnd + ENERGY_MAX_EXTENSION_SECONDS,
|
||||
);
|
||||
const sequenceInterval = realignedSequence?.[index] ?? null;
|
||||
const activeInterval =
|
||||
sequenceInterval ??
|
||||
findBestActiveInterval(
|
||||
intervals,
|
||||
searchStart,
|
||||
searchEnd,
|
||||
localStart,
|
||||
localEnd,
|
||||
);
|
||||
|
||||
if (!activeInterval) {
|
||||
previousEnd = segment.end;
|
||||
return segment;
|
||||
}
|
||||
|
||||
const sequenceEndBound =
|
||||
sequenceInterval && localEnd >= activeInterval.start
|
||||
? timelineOffset + localEnd + ENERGY_MAX_EXTENSION_SECONDS
|
||||
: timelineOffset + duration;
|
||||
const nextSequenceStart = realignedSequence?.[index + 1]?.start;
|
||||
const refinedStart = Math.max(
|
||||
timelineOffset,
|
||||
previousEnd + 0.01,
|
||||
timelineOffset + activeInterval.start - ENERGY_BOUNDARY_PADDING_SECONDS,
|
||||
);
|
||||
const sequenceDurationBound = sequenceInterval
|
||||
? refinedStart + getEstimatedCaptionSpeechSeconds(segment.text)
|
||||
: timelineOffset + duration;
|
||||
const refinedEnd = Math.min(
|
||||
timelineOffset + duration,
|
||||
sequenceInterval
|
||||
? timelineOffset + (Number.isFinite(nextSequenceStart) ? nextSequenceStart - 0.05 : duration)
|
||||
: timelineOffset + localEnd + ENERGY_MAX_EXTENSION_SECONDS,
|
||||
sequenceEndBound,
|
||||
sequenceDurationBound,
|
||||
sequenceInterval ? timelineOffset + duration : timelineOffset + nextLocalStart - 0.05,
|
||||
Math.max(refinedStart + MIN_CAPTION_DURATION, timelineOffset + activeInterval.end + 0.16),
|
||||
);
|
||||
|
||||
if (refinedEnd - refinedStart < MIN_CAPTION_DURATION) {
|
||||
previousEnd = segment.end;
|
||||
return segment;
|
||||
}
|
||||
|
||||
previousEnd = refinedEnd;
|
||||
return {
|
||||
...segment,
|
||||
start: refinedStart,
|
||||
end: refinedEnd,
|
||||
rawStart: segment.rawStart ?? segment.start,
|
||||
rawEnd: segment.rawEnd ?? segment.end,
|
||||
timingSource: "asr-energy",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeTokenId(value) {
|
||||
if (typeof value === "bigint") {
|
||||
return Number(value);
|
||||
}
|
||||
const normalized = Number(value);
|
||||
return Number.isFinite(normalized) ? normalized : null;
|
||||
}
|
||||
|
||||
function getGeneratedTokenIds(output) {
|
||||
const tensorLike = output?.sequences ?? output;
|
||||
const rawTokens =
|
||||
tensorLike?.[0] && typeof tensorLike[0].tolist === "function"
|
||||
? tensorLike[0].tolist()
|
||||
: typeof tensorLike?.tolist === "function"
|
||||
? tensorLike.tolist()
|
||||
: tensorLike;
|
||||
const firstSequence = Array.isArray(rawTokens?.[0]) ? rawTokens[0] : rawTokens;
|
||||
return Array.isArray(firstSequence)
|
||||
? firstSequence.map(normalizeTokenId).filter((token) => token !== null)
|
||||
: [];
|
||||
}
|
||||
|
||||
function getWhisperLanguageIdMap(transcriber) {
|
||||
const langToId = transcriber?.model?.generation_config?.lang_to_id;
|
||||
if (!langToId) {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
return new Map(
|
||||
Object.entries(langToId)
|
||||
.map(([token, id]) => {
|
||||
const language = normalizeWhisperLanguageToken(token);
|
||||
return [normalizeTokenId(id), language];
|
||||
})
|
||||
.filter(([id, language]) => id !== null && language),
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeWhisperLanguageToken(token) {
|
||||
const normalized = String(token ?? "").match(/^<\|?([a-z_]+)\|?>$/i)?.[1];
|
||||
return normalized || String(token ?? "").replace(/[<|>]/g, "");
|
||||
}
|
||||
|
||||
function getPreferredWhisperLanguage(preferredLanguage) {
|
||||
return UI_LANGUAGE_TO_WHISPER_LANGUAGE[preferredLanguage] ?? "zh";
|
||||
}
|
||||
|
||||
function getLanguageDetectionSample(audio) {
|
||||
const sampleLength = Math.min(audio.length, ASR_SAMPLE_RATE * LANGUAGE_DETECTION_SECONDS);
|
||||
return audio.subarray(0, sampleLength);
|
||||
}
|
||||
|
||||
function isMultilingualWhisper(transcriber) {
|
||||
return Boolean(transcriber?.model?.generation_config?.is_multilingual);
|
||||
}
|
||||
|
||||
function createModelLoadProgressCallback(onProgress) {
|
||||
const progressByFile = new Map();
|
||||
let reportedProgress = 8;
|
||||
|
||||
return (event) => {
|
||||
const rawProgress = Number(event?.progress);
|
||||
if (!Number.isFinite(rawProgress)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fileKey = event.file ?? event.name ?? event.url ?? "__model__";
|
||||
progressByFile.set(fileKey, Math.max(0, Math.min(100, rawProgress)));
|
||||
const totalProgress = Array.from(progressByFile.values()).reduce((sum, value) => sum + value, 0);
|
||||
const averageProgress = totalProgress / progressByFile.size;
|
||||
const nextProgress = Math.min(70, Math.max(8, Math.round(8 + averageProgress * 0.62)));
|
||||
if (nextProgress <= reportedProgress) {
|
||||
return;
|
||||
}
|
||||
|
||||
reportedProgress = nextProgress;
|
||||
onProgress?.({
|
||||
progress: nextProgress,
|
||||
phase: `下载或读取 ${AUTOMATIC_CAPTION_MODEL_LABEL} ONNX`,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
async function detectWhisperLanguage(transcriber, audio, preferredLanguage, onProgress) {
|
||||
const generationConfig = transcriber?.model?.generation_config;
|
||||
const fallbackLanguage = getPreferredWhisperLanguage(preferredLanguage);
|
||||
if (!isMultilingualWhisper(transcriber)) {
|
||||
return { language: "en", detected: false };
|
||||
}
|
||||
|
||||
const languageIdMap = getWhisperLanguageIdMap(transcriber);
|
||||
if (!languageIdMap.size) {
|
||||
return { language: fallbackLanguage, detected: false };
|
||||
}
|
||||
|
||||
const decoderStartTokenId = normalizeTokenId(generationConfig.decoder_start_token_id);
|
||||
if (decoderStartTokenId === null) {
|
||||
return { language: fallbackLanguage, detected: false };
|
||||
}
|
||||
|
||||
try {
|
||||
onProgress?.({ progress: 70, phase: "识别音频语言" });
|
||||
const sample = getLanguageDetectionSample(audio);
|
||||
const features = await transcriber.processor(sample);
|
||||
const output = await transcriber.model.generate({
|
||||
inputs: features.input_features,
|
||||
decoder_input_ids: [decoderStartTokenId],
|
||||
max_new_tokens: 1,
|
||||
return_timestamps: false,
|
||||
});
|
||||
const tokenIds = getGeneratedTokenIds(output);
|
||||
const languageTokenId = tokenIds.find((token) => token !== decoderStartTokenId && languageIdMap.has(token));
|
||||
const language = languageTokenId === undefined ? null : languageIdMap.get(languageTokenId);
|
||||
|
||||
return {
|
||||
language: language || fallbackLanguage,
|
||||
detected: Boolean(language),
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn("Whisper language detection failed, falling back to preferred language.", error);
|
||||
return { language: fallbackLanguage, detected: false };
|
||||
}
|
||||
}
|
||||
|
||||
async function getTranscriber(onProgress) {
|
||||
if (!transcriberState || transcriberState.modelId !== AUTOMATIC_CAPTION_MODEL_ID) {
|
||||
const modelId = AUTOMATIC_CAPTION_MODEL_ID;
|
||||
transcriberState = {
|
||||
modelId,
|
||||
promise: (async () => {
|
||||
const { pipeline } = await import("@huggingface/transformers");
|
||||
const reportModelLoadProgress = createModelLoadProgressCallback(onProgress);
|
||||
return pipeline("automatic-speech-recognition", modelId, {
|
||||
dtype: "q8",
|
||||
device: "wasm",
|
||||
progress_callback: reportModelLoadProgress,
|
||||
});
|
||||
})(),
|
||||
};
|
||||
}
|
||||
|
||||
return transcriberState.promise;
|
||||
}
|
||||
|
||||
function rejectWorkerRequests(error) {
|
||||
workerRequests.forEach((request) => {
|
||||
request.reject(error);
|
||||
});
|
||||
workerRequests.clear();
|
||||
}
|
||||
|
||||
function getAsrWorker() {
|
||||
if (typeof Worker === "undefined") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (asrWorker) {
|
||||
return asrWorker;
|
||||
}
|
||||
|
||||
asrWorker = new Worker(new URL("../workers/asr.worker.js", import.meta.url), {
|
||||
type: "module",
|
||||
});
|
||||
|
||||
asrWorker.addEventListener("message", (event) => {
|
||||
const message = event.data;
|
||||
const request = workerRequests.get(message?.requestId);
|
||||
if (!request) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "progress") {
|
||||
request.onProgress?.({
|
||||
progress: message.progress,
|
||||
phase: message.phase,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
workerRequests.delete(message.requestId);
|
||||
if (message.type === "result") {
|
||||
request.resolve({
|
||||
output: message.output,
|
||||
language: message.language,
|
||||
languageDetected: Boolean(message.languageDetected),
|
||||
modelId: message.modelId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "error") {
|
||||
request.reject(new Error(message.error || "自动字幕生成失败"));
|
||||
}
|
||||
});
|
||||
|
||||
asrWorker.addEventListener("error", (event) => {
|
||||
const error = new Error(event.message || "自动字幕 Worker 运行失败");
|
||||
asrWorker?.terminate();
|
||||
asrWorker = null;
|
||||
rejectWorkerRequests(error);
|
||||
});
|
||||
|
||||
return asrWorker;
|
||||
}
|
||||
|
||||
function transcribeAudioInWorker(audio, { onProgress, preferredLanguage }) {
|
||||
if (shouldSkipAsrWorker) {
|
||||
return Promise.reject(new Error("本轮已停用自动字幕 Worker。"));
|
||||
}
|
||||
|
||||
const worker = getAsrWorker();
|
||||
if (!worker) {
|
||||
return Promise.reject(new Error("当前浏览器不支持 Worker 自动字幕。"));
|
||||
}
|
||||
|
||||
const requestId = makeId("asr");
|
||||
const transferableAudio = audio.slice();
|
||||
return new Promise((resolve, reject) => {
|
||||
workerRequests.set(requestId, {
|
||||
resolve,
|
||||
reject,
|
||||
onProgress,
|
||||
});
|
||||
|
||||
worker.postMessage(
|
||||
{
|
||||
type: "transcribe",
|
||||
requestId,
|
||||
modelId: AUTOMATIC_CAPTION_MODEL_ID,
|
||||
audioBuffer: transferableAudio.buffer,
|
||||
preferredLanguage,
|
||||
},
|
||||
[transferableAudio.buffer],
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function transcribeAudioOnMainThread(audio, { onProgress, preferredLanguage }) {
|
||||
const transcriber = await getTranscriber(onProgress);
|
||||
const languageResult = await detectWhisperLanguage(transcriber, audio, preferredLanguage, onProgress);
|
||||
const languageLabel = WHISPER_LANGUAGE_NAMES[languageResult.language] ?? languageResult.language.toUpperCase();
|
||||
onProgress?.({
|
||||
progress: 74,
|
||||
phase: `${languageResult.detected ? "检测为" : "按"} ${languageLabel} 转写字幕`,
|
||||
});
|
||||
const transcriptionOptions = {
|
||||
chunk_length_s: 30,
|
||||
max_new_tokens: 224,
|
||||
no_repeat_ngram_size: 3,
|
||||
repetition_penalty: 1.15,
|
||||
stride_length_s: 5,
|
||||
return_timestamps: true,
|
||||
};
|
||||
if (isMultilingualWhisper(transcriber)) {
|
||||
transcriptionOptions.language = languageResult.language;
|
||||
transcriptionOptions.task = "transcribe";
|
||||
}
|
||||
const output = await transcriber(audio, transcriptionOptions);
|
||||
|
||||
return {
|
||||
output,
|
||||
language: languageResult.language,
|
||||
languageDetected: languageResult.detected,
|
||||
modelId: AUTOMATIC_CAPTION_MODEL_ID,
|
||||
source: "main",
|
||||
};
|
||||
}
|
||||
|
||||
function getTranscriptText(output) {
|
||||
const chunkText = Array.isArray(output?.chunks)
|
||||
? output.chunks.map((chunk) => chunk?.text ?? "").join("")
|
||||
: "";
|
||||
return String(chunkText || output?.text || "").replace(/\s+/g, "");
|
||||
}
|
||||
|
||||
function countPattern(text, pattern) {
|
||||
return text.match(pattern)?.length ?? 0;
|
||||
}
|
||||
|
||||
function isSuspiciousChineseTranscript(output) {
|
||||
const text = getTranscriptText(output);
|
||||
const visibleCount = countPattern(text, /[^\s]/g);
|
||||
if (visibleCount < CHINESE_VISIBLE_CHAR_THRESHOLD) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const cjkCount = countPattern(text, /[\u3400-\u9fff]/g);
|
||||
const latinCount = countPattern(text, /[A-Za-zÀ-ÖØ-öø-ÿ]/g);
|
||||
const latinRatio = latinCount / visibleCount;
|
||||
const cjkRatio = cjkCount / visibleCount;
|
||||
const hasLongLatinRun = /[A-Za-zÀ-ÖØ-öø-ÿ]{12,}/.test(text);
|
||||
|
||||
return cjkCount === 0 || (latinRatio > 0.45 && cjkRatio < 0.2) || hasLongLatinRun;
|
||||
}
|
||||
|
||||
function isSuspiciousTranscript(output, language, preferredLanguage) {
|
||||
const expectedLanguage = language || getPreferredWhisperLanguage(preferredLanguage);
|
||||
return expectedLanguage === "zh" && isSuspiciousChineseTranscript(output);
|
||||
}
|
||||
|
||||
function resetAsrWorker() {
|
||||
asrWorker?.terminate();
|
||||
asrWorker = null;
|
||||
workerRequests.clear();
|
||||
}
|
||||
|
||||
export async function transcribeAudioToCaptionSegments(
|
||||
blob,
|
||||
{ onProgress, preferredLanguage = "zh", timelineOffset = 0 } = {},
|
||||
) {
|
||||
onProgress?.({ progress: 5, phase: "解码原声音频" });
|
||||
const { audio, duration } = await decodeAudioForAsr(blob);
|
||||
if (!audio.length || !duration) {
|
||||
throw new Error("没有检测到可识别的音频。");
|
||||
}
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = await transcribeAudioInWorker(audio, { onProgress, preferredLanguage });
|
||||
result.source = "worker";
|
||||
} catch (error) {
|
||||
console.warn("ASR worker failed, falling back to main thread.", error);
|
||||
onProgress?.({ progress: 8, phase: "Worker 不可用,切换主线程自动字幕" });
|
||||
result = await transcribeAudioOnMainThread(audio, { onProgress, preferredLanguage });
|
||||
}
|
||||
|
||||
if (result.source === "worker" && isSuspiciousTranscript(result.output, result.language, preferredLanguage)) {
|
||||
console.warn("ASR worker returned a suspicious transcript, retrying on the WASM main thread.", result.output);
|
||||
shouldSkipAsrWorker = true;
|
||||
resetAsrWorker();
|
||||
onProgress?.({ progress: 78, phase: "Worker 结果异常,切换稳定 WASM 重新识别" });
|
||||
result = await transcribeAudioOnMainThread(audio, { onProgress, preferredLanguage });
|
||||
}
|
||||
|
||||
if (isSuspiciousTranscript(result.output, result.language, preferredLanguage)) {
|
||||
throw new Error("自动字幕结果像是识别错语言了,请刷新后重新生成一次。");
|
||||
}
|
||||
|
||||
const rawSegments = outputToCaptionSegments(
|
||||
result.output,
|
||||
duration,
|
||||
Math.max(0, timelineOffset || 0),
|
||||
result.language,
|
||||
);
|
||||
const segments = refineCaptionSegmentsWithAudioEnergy(
|
||||
rawSegments,
|
||||
audio,
|
||||
duration,
|
||||
Math.max(0, timelineOffset || 0),
|
||||
);
|
||||
if (!segments.length) {
|
||||
throw new Error("没有识别到可用字幕。");
|
||||
}
|
||||
|
||||
onProgress?.({ progress: 96, phase: "写入字幕轨道" });
|
||||
return {
|
||||
segments,
|
||||
text: segments.map((segment) => segment.text).join("\n"),
|
||||
duration,
|
||||
language: result.language,
|
||||
languageDetected: result.languageDetected,
|
||||
};
|
||||
}
|
||||
+145
-10
@@ -28,6 +28,95 @@ export function getAudioRecordingFormat() {
|
||||
let ffmpegLoadPromise = null;
|
||||
let ffmpegTaskQueue = Promise.resolve();
|
||||
|
||||
const VIDEO_TRACK_FRAME_MAX = 72;
|
||||
const VIDEO_TRACK_FRAME_HEIGHT = 90;
|
||||
|
||||
function getVideoTrackSampleCount(duration, maxFrames = VIDEO_TRACK_FRAME_MAX) {
|
||||
const safeDuration = Math.max(0, Number.isFinite(duration) ? duration : 0);
|
||||
if (!safeDuration) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const targetStep =
|
||||
safeDuration <= 20
|
||||
? 0.5
|
||||
: safeDuration <= 120
|
||||
? 1.25
|
||||
: safeDuration <= 600
|
||||
? 3
|
||||
: 10;
|
||||
|
||||
return Math.max(1, Math.min(maxFrames, Math.ceil(safeDuration / targetStep)));
|
||||
}
|
||||
|
||||
function seekVideoFrame(video, time) {
|
||||
const safeTime = Math.max(0, Math.min(time, Math.max(0, (video.duration || time) - 0.04)));
|
||||
if (video.readyState >= 2 && Math.abs(video.currentTime - safeTime) < 0.015) {
|
||||
return new Promise((resolve) => window.requestAnimationFrame(resolve));
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const cleanup = () => {
|
||||
video.removeEventListener("seeked", handleSeeked);
|
||||
video.removeEventListener("error", handleError);
|
||||
};
|
||||
const handleSeeked = () => {
|
||||
cleanup();
|
||||
window.requestAnimationFrame(resolve);
|
||||
};
|
||||
const handleError = () => {
|
||||
cleanup();
|
||||
reject(new Error("Video frame seek failed"));
|
||||
};
|
||||
|
||||
video.addEventListener("seeked", handleSeeked, { once: true });
|
||||
video.addEventListener("error", handleError, { once: true });
|
||||
video.currentTime = safeTime;
|
||||
});
|
||||
}
|
||||
|
||||
export async function extractVideoTrackFrames(src, options = {}) {
|
||||
const {
|
||||
duration,
|
||||
width,
|
||||
height,
|
||||
maxFrames = VIDEO_TRACK_FRAME_MAX,
|
||||
quality = 0.72,
|
||||
} = options;
|
||||
const video = await loadVideo(src);
|
||||
const safeDuration = Math.max(0, duration || video.duration || 0);
|
||||
const frameCount = getVideoTrackSampleCount(safeDuration, maxFrames);
|
||||
if (!frameCount) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const naturalWidth = Math.max(1, width || video.videoWidth || 16);
|
||||
const naturalHeight = Math.max(1, height || video.videoHeight || 9);
|
||||
const aspectRatio = naturalWidth / naturalHeight;
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.height = VIDEO_TRACK_FRAME_HEIGHT;
|
||||
canvas.width = Math.max(36, Math.min(180, Math.round(canvas.height * aspectRatio)));
|
||||
const context = canvas.getContext("2d", { alpha: false });
|
||||
if (!context) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const frames = [];
|
||||
video.pause();
|
||||
for (let index = 0; index < frameCount; index += 1) {
|
||||
const time = ((index + 0.5) / frameCount) * safeDuration;
|
||||
await seekVideoFrame(video, time);
|
||||
context.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||||
frames.push(canvas.toDataURL("image/jpeg", quality));
|
||||
}
|
||||
return frames;
|
||||
} finally {
|
||||
video.removeAttribute("src");
|
||||
video.load();
|
||||
}
|
||||
}
|
||||
|
||||
export async function decodeWaveform(blob, barCount = 118) {
|
||||
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
|
||||
if (!AudioContextClass) {
|
||||
@@ -142,8 +231,9 @@ function drawPreviewFrame(context, visual, canvas, options) {
|
||||
captionsEnabled = true,
|
||||
captionPosition = "bottom",
|
||||
captionPlacement = null,
|
||||
captionSize = 34,
|
||||
captionSize = 12,
|
||||
sticker = null,
|
||||
stickerImage = null,
|
||||
transitionId = "none",
|
||||
} = options;
|
||||
|
||||
@@ -175,7 +265,15 @@ function drawPreviewFrame(context, visual, canvas, options) {
|
||||
context.fillText(subtitle.slice(0, 34), overlayX + overlayWidth / 2, overlayY + overlayHeight * 0.62);
|
||||
}
|
||||
|
||||
if (sticker?.text) {
|
||||
if (sticker?.src && stickerImage) {
|
||||
const stickerRatio =
|
||||
(stickerImage.naturalWidth || stickerImage.width || 1) /
|
||||
(stickerImage.naturalHeight || stickerImage.height || 1);
|
||||
const maxStickerSize = Math.min(width, height) * 0.22;
|
||||
const stickerWidth = stickerRatio >= 1 ? maxStickerSize : maxStickerSize * stickerRatio;
|
||||
const stickerHeight = stickerRatio >= 1 ? maxStickerSize / stickerRatio : maxStickerSize;
|
||||
context.drawImage(stickerImage, width - stickerWidth - width * 0.1, height * 0.1, stickerWidth, stickerHeight);
|
||||
} else if (sticker?.text) {
|
||||
context.fillStyle = "rgba(53, 240, 221, 0.92)";
|
||||
context.fillRect(width - 246, 54, 172, 54);
|
||||
context.fillStyle = "#061515";
|
||||
@@ -256,6 +354,7 @@ export async function exportBrowserVideo({
|
||||
voiceVolume = 1,
|
||||
sourceAudioBlob,
|
||||
sourceAudioVolume = 1,
|
||||
sourceAudioStart = 0,
|
||||
musicBlob,
|
||||
musicVolume = 0.35,
|
||||
text,
|
||||
@@ -269,6 +368,7 @@ export async function exportBrowserVideo({
|
||||
captionPlacement,
|
||||
captionSize,
|
||||
sticker,
|
||||
stickerSegments = [],
|
||||
transitionId,
|
||||
onProgress,
|
||||
}) {
|
||||
@@ -287,6 +387,16 @@ export async function exportBrowserVideo({
|
||||
visual: segment.type === "video" ? await loadVideo(segment.src) : await loadImage(segment.src),
|
||||
})),
|
||||
);
|
||||
const stickerSources = Array.from(
|
||||
new Set([
|
||||
...(sticker?.src ? [sticker.src] : []),
|
||||
...stickerSegments.map((segment) => segment.src).filter(Boolean),
|
||||
]),
|
||||
);
|
||||
const stickerImageEntries = await Promise.all(
|
||||
stickerSources.map(async (src) => [src, await loadImage(src).catch(() => null)]),
|
||||
);
|
||||
const stickerImageMap = new Map(stickerImageEntries.filter(([, image]) => image));
|
||||
onProgress?.({ progress: 8, phase: "准备画布与轨道" });
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = ratio.width;
|
||||
@@ -300,9 +410,11 @@ export async function exportBrowserVideo({
|
||||
const sources = [];
|
||||
let destination = null;
|
||||
const audioInputs = [
|
||||
audioBlob ? { blob: audioBlob, volume: voiceVolume, role: "voice" } : null,
|
||||
sourceAudioBlob ? { blob: sourceAudioBlob, volume: sourceAudioVolume, role: "source" } : null,
|
||||
musicBlob ? { blob: musicBlob, volume: musicVolume, role: "music" } : null,
|
||||
audioBlob ? { blob: audioBlob, volume: voiceVolume, role: "voice", start: 0 } : null,
|
||||
sourceAudioBlob
|
||||
? { blob: sourceAudioBlob, volume: sourceAudioVolume, role: "source", start: Math.max(0, sourceAudioStart || 0) }
|
||||
: null,
|
||||
musicBlob ? { blob: musicBlob, volume: musicVolume, role: "music", start: 0 } : null,
|
||||
].filter(Boolean);
|
||||
|
||||
if (audioInputs.length) {
|
||||
@@ -330,7 +442,10 @@ export async function exportBrowserVideo({
|
||||
gain.gain.value = input.volume;
|
||||
source.connect(gain);
|
||||
gain.connect(destination);
|
||||
sources.push(source);
|
||||
sources.push({
|
||||
node: source,
|
||||
start: input.start,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -345,7 +460,7 @@ export async function exportBrowserVideo({
|
||||
const totalDuration = Math.max(
|
||||
duration,
|
||||
decodedDuration,
|
||||
...sources.map((source) => source.buffer?.duration ?? 0),
|
||||
...sources.map(({ node, start }) => start + (node.buffer?.duration ?? 0)),
|
||||
1,
|
||||
);
|
||||
const captionTargetDuration = decodedDuration || 0;
|
||||
@@ -381,6 +496,22 @@ export async function exportBrowserVideo({
|
||||
range: exportVisualTimeline[Math.max(0, visualIndex)] ?? exportVisualTimeline[0],
|
||||
};
|
||||
};
|
||||
const getStickerAtTime = (elapsed) => {
|
||||
if (!stickerSegments.length) {
|
||||
return sticker;
|
||||
}
|
||||
|
||||
for (let index = stickerSegments.length - 1; index >= 0; index -= 1) {
|
||||
const segment = stickerSegments[index];
|
||||
const start = Math.max(0, segment.start || 0);
|
||||
const end = start + Math.max(0, segment.duration || 0);
|
||||
if (elapsed >= start && elapsed < end) {
|
||||
return segment;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
const draw = () => {
|
||||
const elapsed = Math.min(totalDuration, (performance.now() - startTime) / 1000);
|
||||
const segmentIndex = getSegmentIndexAtTime(exportSegments, elapsed, captionTargetDuration);
|
||||
@@ -394,6 +525,7 @@ export async function exportBrowserVideo({
|
||||
visualItem.visual.currentTime = nextVideoTime;
|
||||
}
|
||||
}
|
||||
const exportSticker = getStickerAtTime(elapsed);
|
||||
drawPreviewFrame(context, visualItem.visual, canvas, {
|
||||
subtitle: exportCaption,
|
||||
progress: elapsed / totalDuration,
|
||||
@@ -403,7 +535,8 @@ export async function exportBrowserVideo({
|
||||
captionPosition,
|
||||
captionPlacement,
|
||||
captionSize,
|
||||
sticker,
|
||||
sticker: exportSticker,
|
||||
stickerImage: exportSticker?.src ? stickerImageMap.get(exportSticker.src) : null,
|
||||
transitionId,
|
||||
});
|
||||
|
||||
@@ -421,7 +554,7 @@ export async function exportBrowserVideo({
|
||||
};
|
||||
|
||||
draw();
|
||||
sources.forEach((source) => source.start());
|
||||
sources.forEach(({ node, start }) => node.start(start));
|
||||
await new Promise((resolve) => {
|
||||
window.setTimeout(resolve, totalDuration * 1000);
|
||||
});
|
||||
@@ -433,6 +566,7 @@ export async function exportBrowserVideo({
|
||||
});
|
||||
const finalSegmentIndex = getSegmentIndexAtTime(exportSegments, totalDuration, captionTargetDuration);
|
||||
const { item: finalVisualItem } = getVisualItemAtTime(totalDuration);
|
||||
const finalSticker = getStickerAtTime(totalDuration);
|
||||
drawPreviewFrame(context, finalVisualItem.visual, canvas, {
|
||||
subtitle:
|
||||
finalSegmentIndex >= 0 && !exportSegments[finalSegmentIndex]?.hidden
|
||||
@@ -445,7 +579,8 @@ export async function exportBrowserVideo({
|
||||
captionPosition,
|
||||
captionPlacement,
|
||||
captionSize,
|
||||
sticker,
|
||||
sticker: finalSticker,
|
||||
stickerImage: finalSticker?.src ? stickerImageMap.get(finalSticker.src) : null,
|
||||
transitionId,
|
||||
});
|
||||
recorder.stop();
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
const MODEL_CACHE_WORKER_URL = "/model-cache-sw.js";
|
||||
|
||||
export function registerModelCacheServiceWorker() {
|
||||
if (typeof navigator === "undefined" || !("serviceWorker" in navigator)) {
|
||||
return;
|
||||
}
|
||||
|
||||
navigator.serviceWorker
|
||||
.register(MODEL_CACHE_WORKER_URL)
|
||||
.then((registration) => registration.update().catch(() => {}))
|
||||
.catch((error) => {
|
||||
console.warn("Model cache service worker registration failed.", error);
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
DEFAULT_STICKER_SEGMENT_SECONDS,
|
||||
MAX_CAPTION_SEGMENT_SECONDS,
|
||||
MAX_IMAGE_THUMBNAILS,
|
||||
MAX_TIMELINE_DURATION_SECONDS,
|
||||
@@ -7,6 +8,8 @@ import {
|
||||
IMAGE_SEGMENT_SECONDS,
|
||||
} from "../config/editor.js";
|
||||
|
||||
const MIN_TIMED_CAPTION_SECONDS = 0.2;
|
||||
|
||||
export function makeId(prefix) {
|
||||
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
@@ -30,6 +33,9 @@ export function getVisualAssetPayload(asset) {
|
||||
name: asset.name ?? "",
|
||||
meta: asset.meta ?? "",
|
||||
blob: asset.blob ?? null,
|
||||
width: asset.width ?? asset.naturalWidth ?? 0,
|
||||
height: asset.height ?? asset.naturalHeight ?? 0,
|
||||
trackFrames: Array.isArray(asset.trackFrames) ? asset.trackFrames : [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -41,6 +47,45 @@ export function createVisualSegment(duration = 4, asset = null) {
|
||||
};
|
||||
}
|
||||
|
||||
export function createStickerSegment(sticker, start = 0, duration = DEFAULT_STICKER_SEGMENT_SECONDS) {
|
||||
const safeDuration = Math.max(
|
||||
MIN_VISUAL_SEGMENT_SECONDS,
|
||||
Math.min(MAX_TIMELINE_DURATION_SECONDS, duration || DEFAULT_STICKER_SEGMENT_SECONDS),
|
||||
);
|
||||
|
||||
return {
|
||||
id: makeId("sticker"),
|
||||
stickerId: sticker?.stickerId ?? sticker?.id ?? "",
|
||||
name: sticker?.name ?? "",
|
||||
nameEn: sticker?.nameEn ?? "",
|
||||
category: sticker?.category ?? "",
|
||||
src: sticker?.src ?? "",
|
||||
start: Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - safeDuration, start || 0)),
|
||||
duration: safeDuration,
|
||||
};
|
||||
}
|
||||
|
||||
export function getTimedSegmentsEnd(segments) {
|
||||
return segments.reduce(
|
||||
(end, segment) => Math.max(end, Math.max(0, segment.start || 0) + Math.max(0, segment.duration || 0)),
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
export function getTimedSegmentIndexAtTime(segments, time) {
|
||||
const safeTime = Math.max(0, Number.isFinite(time) ? time : 0);
|
||||
for (let index = segments.length - 1; index >= 0; index -= 1) {
|
||||
const segment = segments[index];
|
||||
const start = Math.max(0, segment.start || 0);
|
||||
const end = start + Math.max(0, segment.duration || 0);
|
||||
if (safeTime >= start && safeTime < end) {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
export function getVisualSegmentsTotal(segments) {
|
||||
return segments.reduce((sum, segment) => sum + Math.max(0, segment.duration || 0), 0);
|
||||
}
|
||||
@@ -107,13 +152,39 @@ export function getCaptionBaseDuration(text) {
|
||||
}
|
||||
|
||||
export function getCaptionSegmentDuration(segment) {
|
||||
if (hasExplicitCaptionTiming(segment)) {
|
||||
return Math.max(MIN_TIMED_CAPTION_SECONDS, segment.end - segment.start);
|
||||
}
|
||||
|
||||
const defaultWeight = getCaptionDefaultWeight(segment.text);
|
||||
const weight = Number.isFinite(segment.weight) ? segment.weight : defaultWeight;
|
||||
const weightScale = Math.max(0.35, weight / defaultWeight);
|
||||
return getCaptionBaseDuration(segment.text) * weightScale;
|
||||
}
|
||||
|
||||
export function hasExplicitCaptionTiming(segment) {
|
||||
return Number.isFinite(segment?.start) && Number.isFinite(segment?.end) && segment.end > segment.start;
|
||||
}
|
||||
|
||||
export function getCaptionTimeline(captionSegments, targetDuration = 0) {
|
||||
if (captionSegments.some(hasExplicitCaptionTiming)) {
|
||||
let cursor = 0;
|
||||
return captionSegments.map((segment) => {
|
||||
const hasTiming = hasExplicitCaptionTiming(segment);
|
||||
const start = hasTiming ? Math.max(0, segment.start) : cursor;
|
||||
const duration = hasTiming
|
||||
? Math.max(MIN_TIMED_CAPTION_SECONDS, segment.end - segment.start)
|
||||
: getCaptionSegmentDuration(segment);
|
||||
const timelineItem = {
|
||||
start,
|
||||
end: start + duration,
|
||||
duration,
|
||||
};
|
||||
cursor = timelineItem.end;
|
||||
return timelineItem;
|
||||
});
|
||||
}
|
||||
|
||||
const naturalDurations = captionSegments.map((segment) => getCaptionSegmentDuration(segment));
|
||||
const naturalTotal = naturalDurations.reduce((sum, duration) => sum + duration, 0);
|
||||
const shouldAlignToTarget = targetDuration > 0 && naturalTotal > 0;
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { MAX_TIMELINE_DURATION_SECONDS } from "../config/editor.js";
|
||||
|
||||
export const TIMELINE_MIN_ZOOM = 0.25;
|
||||
export const TIMELINE_MAX_ZOOM = 16;
|
||||
export const TIMELINE_DEFAULT_VISIBLE_SECONDS = 10;
|
||||
export const TIMELINE_MIN_VISIBLE_SECONDS = 0.5;
|
||||
export const TIMELINE_FRAME_RATE = 30;
|
||||
|
||||
const ZOOM_IN_CURVE = Math.log(TIMELINE_DEFAULT_VISIBLE_SECONDS / TIMELINE_MIN_VISIBLE_SECONDS) /
|
||||
Math.log(TIMELINE_MAX_ZOOM);
|
||||
|
||||
export function clampTimelineZoom(zoom) {
|
||||
return Math.max(TIMELINE_MIN_ZOOM, Math.min(TIMELINE_MAX_ZOOM, zoom));
|
||||
}
|
||||
|
||||
export function getTimelineVisibleDuration(zoom) {
|
||||
const clampedZoom = clampTimelineZoom(zoom);
|
||||
|
||||
if (clampedZoom <= 1) {
|
||||
const progress = (clampedZoom - TIMELINE_MIN_ZOOM) / (1 - TIMELINE_MIN_ZOOM);
|
||||
const maxLog = Math.log(MAX_TIMELINE_DURATION_SECONDS);
|
||||
const defaultLog = Math.log(TIMELINE_DEFAULT_VISIBLE_SECONDS);
|
||||
return Math.exp(maxLog + (defaultLog - maxLog) * progress);
|
||||
}
|
||||
|
||||
return Math.max(
|
||||
TIMELINE_MIN_VISIBLE_SECONDS,
|
||||
TIMELINE_DEFAULT_VISIBLE_SECONDS / Math.pow(clampedZoom, ZOOM_IN_CURVE),
|
||||
);
|
||||
}
|
||||
|
||||
export function getTimelineTrackWidthPercent(timelineDuration, zoom) {
|
||||
if (timelineDuration <= 0) {
|
||||
return 100;
|
||||
}
|
||||
|
||||
const visibleDuration = getTimelineVisibleDuration(zoom);
|
||||
return Math.max(100, (timelineDuration / visibleDuration) * 100);
|
||||
}
|
||||
|
||||
export function getTimelineRulerScale(visibleDuration) {
|
||||
if (visibleDuration <= 0.75) {
|
||||
return { minorStep: 1 / TIMELINE_FRAME_RATE, majorStep: 0.5, labelMode: "frames" };
|
||||
}
|
||||
if (visibleDuration <= 2) {
|
||||
return { minorStep: 0.1, majorStep: 0.5, labelMode: "subseconds" };
|
||||
}
|
||||
if (visibleDuration <= 6) {
|
||||
return { minorStep: 0.25, majorStep: 0.5, labelMode: "subseconds" };
|
||||
}
|
||||
if (visibleDuration <= 16) {
|
||||
return { minorStep: 0.5, majorStep: 1, labelMode: "seconds" };
|
||||
}
|
||||
if (visibleDuration <= 45) {
|
||||
return { minorStep: 1, majorStep: 5, labelMode: "seconds" };
|
||||
}
|
||||
if (visibleDuration <= 120) {
|
||||
return { minorStep: 5, majorStep: 15, labelMode: "seconds" };
|
||||
}
|
||||
if (visibleDuration <= 420) {
|
||||
return { minorStep: 15, majorStep: 60, labelMode: "minutes" };
|
||||
}
|
||||
if (visibleDuration <= 900) {
|
||||
return { minorStep: 60, majorStep: 300, labelMode: "minutes" };
|
||||
}
|
||||
return { minorStep: 300, majorStep: 600, labelMode: "minutes" };
|
||||
}
|
||||
|
||||
export function getTimelineRulerTicks(timelineDuration, zoom, visibleStart = 0, visibleEnd = timelineDuration) {
|
||||
if (timelineDuration <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const visibleDuration = getTimelineVisibleDuration(zoom);
|
||||
const { minorStep, majorStep, labelMode } = getTimelineRulerScale(visibleDuration);
|
||||
const rangePadding = Math.max(visibleDuration * 0.35, majorStep);
|
||||
const rangeStart = Math.max(0, visibleStart - rangePadding);
|
||||
const rangeEnd = Math.min(timelineDuration, visibleEnd + rangePadding);
|
||||
const startIndex = Math.max(0, Math.floor(rangeStart / minorStep));
|
||||
const endIndex = Math.max(startIndex, Math.ceil(rangeEnd / minorStep));
|
||||
|
||||
return Array.from({ length: endIndex - startIndex + 1 }, (_, offset) => {
|
||||
const index = startIndex + offset;
|
||||
const time = Math.min(timelineDuration, index * minorStep);
|
||||
const isMajor = Math.abs(time / majorStep - Math.round(time / majorStep)) < 0.001;
|
||||
return {
|
||||
id: `${minorStep}-${index}`,
|
||||
time,
|
||||
left: (time / timelineDuration) * 100,
|
||||
isMajor,
|
||||
label: isMajor ? formatTimelineRulerLabel(time, labelMode) : "",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function getTimelineZoomLabel(zoom) {
|
||||
const visibleDuration = getTimelineVisibleDuration(zoom);
|
||||
|
||||
if (visibleDuration <= 0.75) {
|
||||
return "15f";
|
||||
}
|
||||
|
||||
if (visibleDuration < 2) {
|
||||
return `${visibleDuration.toFixed(1)}s`;
|
||||
}
|
||||
|
||||
if (visibleDuration < 60) {
|
||||
return `${Math.round(visibleDuration)}s`;
|
||||
}
|
||||
|
||||
return `${Math.round(visibleDuration / 60)}m`;
|
||||
}
|
||||
|
||||
export function formatTimelineRulerLabel(value, mode = "seconds") {
|
||||
const safeSeconds = Math.max(0, Number.isFinite(value) ? value : 0);
|
||||
const minutes = Math.floor(safeSeconds / 60);
|
||||
const seconds = Math.floor(safeSeconds % 60);
|
||||
const frame = Math.round((safeSeconds - Math.floor(safeSeconds)) * TIMELINE_FRAME_RATE);
|
||||
const centiseconds = Math.round((safeSeconds - Math.floor(safeSeconds)) * 100);
|
||||
const clock = `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
|
||||
|
||||
if (mode === "frames" && frame > 0) {
|
||||
return `${clock}:${String(frame).padStart(2, "0")}f`;
|
||||
}
|
||||
|
||||
if (mode === "subseconds" && centiseconds > 0) {
|
||||
return `${clock}.${String(centiseconds).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
return clock;
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
const CHINESE_SPOKEN_DIGITS = {
|
||||
0: "零",
|
||||
1: "一",
|
||||
2: "二",
|
||||
3: "三",
|
||||
4: "四",
|
||||
5: "五",
|
||||
6: "六",
|
||||
7: "七",
|
||||
8: "八",
|
||||
9: "九",
|
||||
};
|
||||
|
||||
const CHINESE_SPOKEN_LETTERS = {
|
||||
A: "诶",
|
||||
B: "比",
|
||||
C: "西",
|
||||
D: "迪",
|
||||
E: "伊",
|
||||
F: "艾弗",
|
||||
G: "吉",
|
||||
H: "艾尺",
|
||||
I: "艾",
|
||||
J: "杰",
|
||||
K: "开",
|
||||
L: "艾勒",
|
||||
M: "艾姆",
|
||||
N: "恩",
|
||||
O: "欧",
|
||||
P: "皮",
|
||||
Q: "丘",
|
||||
R: "阿尔",
|
||||
S: "艾斯",
|
||||
T: "提",
|
||||
U: "优",
|
||||
V: "维",
|
||||
W: "达不溜",
|
||||
X: "艾克斯",
|
||||
Y: "歪",
|
||||
Z: "泽德",
|
||||
};
|
||||
|
||||
const ASCII_PUNCTUATION_MAP = new Map([
|
||||
[",", ","],
|
||||
[".", "。"],
|
||||
["?", "?"],
|
||||
["!", "!"],
|
||||
[";", ";"],
|
||||
[":", ":"],
|
||||
]);
|
||||
|
||||
export class TtsInputError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = "TtsInputError";
|
||||
}
|
||||
}
|
||||
|
||||
function countMatches(text, pattern) {
|
||||
return text.match(pattern)?.join("").length ?? 0;
|
||||
}
|
||||
|
||||
function normalizeBaseText(text) {
|
||||
return text
|
||||
.normalize("NFKC")
|
||||
.replace(/[\u200B-\u200D\uFEFF]/g, "")
|
||||
.replace(/[“”"']/g, "")
|
||||
.replace(/\r\n?/g, "\n")
|
||||
.trim();
|
||||
}
|
||||
|
||||
function speakShortLatinTokenInChinese(token) {
|
||||
return [...token.toUpperCase()]
|
||||
.map((char) => CHINESE_SPOKEN_DIGITS[char] ?? CHINESE_SPOKEN_LETTERS[char] ?? "")
|
||||
.join("");
|
||||
}
|
||||
|
||||
function prepareChinesePiperText(rawText) {
|
||||
const normalized = normalizeBaseText(rawText);
|
||||
const latinCount = countMatches(normalized, /[A-Za-z]/g);
|
||||
const hanCount = countMatches(normalized, /\p{Script=Han}/gu);
|
||||
|
||||
if (latinCount > Math.max(14, hanCount * 0.8)) {
|
||||
throw new TtsInputError("当前中文语音不适合大量英文文案,请切换 English 声音后再生成。");
|
||||
}
|
||||
|
||||
let changed = false;
|
||||
let text = normalized
|
||||
.replace(/[A-Za-z0-9]+/g, (token) => {
|
||||
changed = true;
|
||||
return token.length <= 8 ? speakShortLatinTokenInChinese(token) : ",";
|
||||
})
|
||||
.replace(/[()()\[\]{}【】<>《》]/g, () => {
|
||||
changed = true;
|
||||
return ",";
|
||||
})
|
||||
.replace(/[-_/\\|~`^+=*@#$%&]/g, () => {
|
||||
changed = true;
|
||||
return ",";
|
||||
})
|
||||
.replace(/[,.?!;:]/g, (mark) => {
|
||||
changed = true;
|
||||
return ASCII_PUNCTUATION_MAP.get(mark) ?? ",";
|
||||
})
|
||||
.replace(/\s+/g, ",")
|
||||
.replace(/[^\p{Script=Han}零一二三四五六七八九十百千万亿两,。!?;:、\n]/gu, () => {
|
||||
changed = true;
|
||||
return "";
|
||||
})
|
||||
.replace(/[,、]{2,}/g, ",")
|
||||
.replace(/[。!?;:]{2,}/g, (marks) => marks[0])
|
||||
.replace(/^[,。!?;:、]+|[,。!?;:、]+$/g, "")
|
||||
.trim();
|
||||
|
||||
if (!text) {
|
||||
throw new TtsInputError("当前中文语音没有可朗读的中文内容,请输入中文或切换英文声音。");
|
||||
}
|
||||
|
||||
return {
|
||||
text,
|
||||
warning: changed ? "已自动清理中文语音不支持的符号,避免本地 ONNX 运行失败。" : "",
|
||||
};
|
||||
}
|
||||
|
||||
function prepareKokoroText(rawText) {
|
||||
const normalized = normalizeBaseText(rawText).replace(/\s+/g, " ");
|
||||
const hanCount = countMatches(normalized, /\p{Script=Han}/gu);
|
||||
const latinCount = countMatches(normalized, /[A-Za-z]/g);
|
||||
|
||||
if (hanCount > Math.max(4, latinCount * 0.5)) {
|
||||
throw new TtsInputError("当前英文语音不适合中文文案,请切换中文声音后再生成。");
|
||||
}
|
||||
|
||||
const text = normalized.replace(/[^\p{Script=Latin}0-9\s.,!?;:'"()\-]/gu, "").trim();
|
||||
if (!text) {
|
||||
throw new TtsInputError("当前英文语音没有可朗读的英文内容,请输入英文或切换中文声音。");
|
||||
}
|
||||
|
||||
return {
|
||||
text,
|
||||
warning: text !== normalized ? "已自动清理英文语音不支持的字符。" : "",
|
||||
};
|
||||
}
|
||||
|
||||
export function prepareTextForVoice(rawText, voice) {
|
||||
if (voice?.engine === "piper" && voice.language === "中文") {
|
||||
return prepareChinesePiperText(rawText);
|
||||
}
|
||||
|
||||
if (voice?.engine === "kokoro") {
|
||||
return prepareKokoroText(rawText);
|
||||
}
|
||||
|
||||
const text = normalizeBaseText(rawText);
|
||||
if (!text) {
|
||||
throw new TtsInputError("请输入要生成的文案。");
|
||||
}
|
||||
return { text, warning: "" };
|
||||
}
|
||||
|
||||
export function isPiperSymbolError(error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return /Gather|indices element out of data bounds|OrtRun|emb\/Gather/i.test(message);
|
||||
}
|
||||
|
||||
export function isStorageQuotaError(error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return /QuotaExceededError|storage quota|exceed.*quota/i.test(message);
|
||||
}
|
||||
|
||||
export async function clearPiperCacheIfStorageTight(tts) {
|
||||
if (!navigator.storage?.estimate || typeof tts?.flush !== "function") {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const estimate = await navigator.storage.estimate();
|
||||
const usage = estimate.usage ?? 0;
|
||||
const quota = estimate.quota ?? 0;
|
||||
const remaining = quota > usage ? quota - usage : 0;
|
||||
if (quota > 0 && (usage / quota > 0.9 || remaining < 120 * 1024 * 1024)) {
|
||||
await tts.flush();
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
Reference in new issue
Block a user