🎥 Make videos programmatically with React
Fix Whisper model progress and timestamps
Jonny Burgerc046b7b60727
diff --git a/packages/docs/docs/whisper-webgpu/load-whisper-model.mdx b/packages/docs/docs/whisper-webgpu/load-whisper-model.mdxindex 4f9b56eef0..ecaad361cb 100644--- a/packages/docs/docs/whisper-webgpu/load-whisper-model.mdx+++ b/packages/docs/docs/whisper-webgpu/load-whisper-model.mdx@@ -13,8 +13,8 @@ import {loadWhisperModel} from '@remotion/whisper-webgpu';const result = await loadWhisperModel({model: 'small.en',- onProgress: ({progress, file}) => {- console.log(file, progress);+ onProgress: ({progress}) => {+ console.log(progress);},});@@ -33,7 +33,7 @@ One of the names returned by [`getAvailableModels()`](/docs/whisper-webgpu/get-a### onProgress?-Called while model files are resolved and downloaded. `progress` is between `0` and `1` when available.+Called while model files are resolved and downloaded. `progress` is the aggregate download progress between `0` and `1` and never decreases.## Return valuediff --git a/packages/whisper-webgpu/src/load-whisper-model.ts b/packages/whisper-webgpu/src/load-whisper-model.tsindex 6e5d211a5c..2811f4fa9d 100644--- a/packages/whisper-webgpu/src/load-whisper-model.ts+++ b/packages/whisper-webgpu/src/load-whisper-model.ts@@ -86,16 +86,54 @@ export const loadWhisperModel = async ({env.backends.onnx.wasm!.numThreads = globalThis.crossOriginIsolated ? 0 : 1;}+ onProgress?.({+ status: 'loading',+ file: null,+ progress: 0,+ loadedBytes: 0,+ totalBytes: null,+ });+const {modelId} = getModelInfo(model);+ let lastProgress = 0;+ let lastLoadedBytes = 0;const loading = pipeline('automatic-speech-recognition', modelId, {device: resolvedBackend,dtype:resolvedBackend === 'webgpu'? {encoder_model: 'fp32', decoder_model_merged: 'q4'}: 'q8',- progress_callback: (event) => {- onProgress?.(normalizeProgress(event as Record<string, unknown>));- },+ progress_callback: onProgress+ ? (event) => {+ const record = event as Record<string, unknown>;+ if (record.status === 'progress_total') {+ const normalized = normalizeProgress(record);+ lastProgress = Math.max(+ lastProgress,+ normalized.progress ?? lastProgress,+ );+ lastLoadedBytes = Math.max(+ lastLoadedBytes,+ normalized.loadedBytes ?? lastLoadedBytes,+ );+ onProgress({+ ...normalized,+ progress: lastProgress,+ loadedBytes: lastLoadedBytes,+ });+ }++ if (record.status === 'ready') {+ onProgress({+ status: 'ready',+ file: null,+ progress: 1,+ loadedBytes: null,+ totalBytes: null,+ });+ }+ }+ : undefined,}) as Promise<LoadedWhisperPipeline>;pipelines.set(cacheKey, loading);diff --git a/packages/whisper-webgpu/src/test/transcribe.test.ts b/packages/whisper-webgpu/src/test/transcribe.test.tsindex 2ac57877db..22b1f60066 100644--- a/packages/whisper-webgpu/src/test/transcribe.test.ts+++ b/packages/whisper-webgpu/src/test/transcribe.test.ts@@ -18,10 +18,12 @@ const fakePipeline = Object.assign((audio: Float32Array, options: Record<string, unknown>) => {transcriptionCall = {audio, options};return Promise.resolve({- text: ' Hello world.',+ text: ' Hello world free today.',chunks: [{text: ' Hello', timestamp: [0.25, 0.75]},- {text: ' world.', timestamp: [1, null]},+ {text: ' world', timestamp: [1, 1.5]},+ {text: ' free', timestamp: [1.8, 1.7]},+ {text: ' today.', timestamp: [2.2, null]},],});},@@ -41,6 +43,44 @@ mock.module('@huggingface/transformers', () => ({options: Record<string, unknown>,) => {pipelineInitialization = {modelId, options};+ const onProgress = options.progress_callback as+ | ((progress: Record<string, unknown>) => void)+ | undefined;+ onProgress?.({status: 'initiate', file: 'encoder_model.onnx'});+ onProgress?.({+ status: 'progress_total',+ progress: 40,+ loaded: 40,+ total: 100,+ });+ onProgress?.({+ status: 'progress',+ file: 'encoder_model.onnx',+ progress: 90,+ loaded: 90,+ total: 100,+ });+ onProgress?.({+ status: 'progress_total',+ progress: 30,+ loaded: 30,+ total: 100,+ });+ onProgress?.({+ status: 'progress',+ file: 'decoder_model_merged.onnx',+ progress: 10,+ loaded: 10,+ total: 100,+ });+ onProgress?.({+ status: 'progress_total',+ progress: 60,+ loaded: 60,+ total: 100,+ });+ onProgress?.({status: 'done', file: 'encoder_model.onnx'});+ onProgress?.({status: 'ready'});return Promise.resolve(fakePipeline);},}));@@ -78,12 +118,14 @@ test('transcribes with timestamps and selects a usable backend', async () => {language: 'en',});expect(result).toEqual({- text: 'Hello world.',+ text: 'Hello world free today.',model: 'small.en',backend: 'wasm',words: [{text: 'Hello', startInSeconds: 0.25, endInSeconds: 0.75},- {text: ' world.', startInSeconds: 1, endInSeconds: 3},+ {text: ' world', startInSeconds: 1, endInSeconds: 1.5},+ {text: ' free', startInSeconds: 1.8, endInSeconds: 2.2},+ {text: ' today.', startInSeconds: 2.2, endInSeconds: 3},],});@@ -97,12 +139,26 @@ test('transcribes with timestamps and selects a usable backend', async () => {confidence: null,},{- text: ' world.',+ text: ' world',startMs: 1000,- endMs: 3000,+ endMs: 1500,+ timestampMs: 1250,+ confidence: null,+ },+ {+ text: ' free',+ startMs: 1800,+ endMs: 2200,timestampMs: 2000,confidence: null,},+ {+ text: ' today.',+ startMs: 2200,+ endMs: 3000,+ timestampMs: 2600,+ confidence: null,+ },],});@@ -203,3 +259,18 @@ test('transcribes with timestamps and selects a usable backend', async () => {await disposeWhisperModel();expect(disposed).toBe(true);});++test('reports aggregate model progress without moving backwards', async () => {+ const {disposeWhisperModel, loadWhisperModel} = await import('../index');+ const progressValues: Array<number | null> = [];+ await loadWhisperModel({+ backend: 'wasm',+ model: 'medium.en',+ onProgress: (progress) => {+ progressValues.push(progress.progress);+ },+ });++ expect(progressValues).toEqual([0, 0.4, 0.4, 0.6, 1]);+ await disposeWhisperModel({backend: 'wasm', model: 'medium.en'});+});diff --git a/packages/whisper-webgpu/src/transcribe.ts b/packages/whisper-webgpu/src/transcribe.tsindex 7f21742c18..8e43d5b8c4 100644--- a/packages/whisper-webgpu/src/transcribe.ts+++ b/packages/whisper-webgpu/src/transcribe.ts@@ -88,20 +88,31 @@ export const transcribe = async ({}const audioDuration = channelWaveform.length / 16_000;- const words = output.chunks.map((chunk, index): WhisperWebGpuWord => {+ const starts = output.chunks.map((chunk) => {const start = chunk.timestamp[0];- const end = Math.min(chunk.timestamp[1] ?? audioDuration, audioDuration);- if (start === null || !Number.isFinite(start) || !Number.isFinite(end)) {+ if (start === null || !Number.isFinite(start)) {throw new Error(`The model returned an invalid timestamp for "${chunk.text}".`,);}- if (end < start) {- throw new Error(- `The model returned a backwards timestamp for "${chunk.text}".`,- );- }+ return Math.max(0, Math.min(start, audioDuration));+ });+ const words = output.chunks.map((chunk, index): WhisperWebGpuWord => {+ const start = starts[index];+ const modelEnd = chunk.timestamp[1];+ const nextStart = starts[index + 1];+ const fallbackEnd =+ nextStart === undefined || nextStart < start ? audioDuration : nextStart;+ const end = Math.max(+ start,+ Math.min(+ modelEnd !== null && Number.isFinite(modelEnd) && modelEnd >= start+ ? modelEnd+ : fallbackEnd,+ audioDuration,+ ),+ );return {text: index === 0 ? chunk.text.trimStart() : chunk.text,