Skip to content

🎥 Make videos programmatically with React

refactor downloadWhisperModel() and update docs

Jonny Burger8d559dcfa4ca
diff --git a/package.json b/package.json
index 81b6a89337..83ca5a82a4 100644
--- a/package.json
+++ b/package.json
@@ -14,6 +14,7 @@
"testlambda": "turbo run testlambda --concurrency=1 --no-update-notifier",
"ci": "turbo run make test --concurrency=1 --no-update-notifier",
"watch": "turbo watch make --concurrency=2 --experimental-write-cache --ui=tui",
+ "watchwhisperwasm": "turbo watch make --experimental-write-cache --filter='@remotion/whisper-wasm'",
"watchwebcodecs": "turbo watch make --experimental-write-cache --filter='@remotion/media-parser' --filter='@remotion/webcodecs'",
"watchcore": "turbo watch make --experimental-write-cache --filter='remotion'",
"watchstudio": "turbo watch make --experimental-write-cache --filter='@remotion/studio' --filter='@remotion/studio-server'",
diff --git a/packages/docs/docs/whisper-wasm/can-use-whisper-wasm.mdx b/packages/docs/docs/whisper-wasm/can-use-whisper-wasm.mdx
index eb6c669ac2..fbd8f17c84 100644
--- a/packages/docs/docs/whisper-wasm/can-use-whisper-wasm.mdx
+++ b/packages/docs/docs/whisper-wasm/can-use-whisper-wasm.mdx
@@ -4,6 +4,10 @@ title: canUseWhisperWasm()
crumb: '@remotion/whisper-wasm'
---
+:::warning
+**Unstable API**: This package is experimental for the moment. As we test it, we might make a few changes to the API.
+:::
+
# canUseWhisperWasm()
Checks if the current browser environment supports running `@remotion/whisper-wasm` with a specified model. This function verifies various browser capabilities like `crossOriginIsolated`, `IndexedDB`, `navigator.storage.estimate()`, and available storage space.
diff --git a/packages/docs/docs/whisper-wasm/download-whisper-model.mdx b/packages/docs/docs/whisper-wasm/download-whisper-model.mdx
index aac9869dd6..95788c23d5 100644
--- a/packages/docs/docs/whisper-wasm/download-whisper-model.mdx
+++ b/packages/docs/docs/whisper-wasm/download-whisper-model.mdx
@@ -5,20 +5,21 @@ crumb: '@remotion/whisper-wasm'
# downloadWhisperModel()
-Downloads a Whisper.cpp model to the browser.
+:::warning
+**Unstable API**: This package is experimental for the moment. As we test it, we might make a few changes to the API.
+:::
-```tsx twoslash title="app.tsx"
-import {useEffect, useState} from 'react';
-import {downloadWhisperModel} from '@remotion/whisper-wasm';
+Downloads a Whisper model into IndexedDB.
-export default function MyApp() {
- const [progress, setProgress] = useState(0);
- useEffect(() => {
- downloadWhisperModel({model: 'tiny.en', onProgress: setProgress});
- }, []);
+```tsx twoslash title="app.ts"
+import {downloadWhisperModel} from '@remotion/whisper-wasm';
- return <h1>my great app</h1>;
-}
+const {alreadyDownloaded} = await downloadWhisperModel({
+ model: 'tiny.en',
+ onProgress: (progress) => {
+ console.log(progress);
+ },
+});
```
## Options
@@ -32,17 +33,21 @@ The model to download. Possible values: `tiny`, `tiny.en`, `base`, `base.en`, `s
Act upon download progress. This is the function signature:
```tsx twoslash
-const onProgress = (progress: number) => {
- // do something
+import {DownloadWhisperModelOnProgress, DownloadWhisperModelProgress} from '@remotion/whisper-wasm';
+
+const onProgress: DownloadWhisperModelOnProgress = ({progress, totalBytes, downloadedBytes}: DownloadWhisperModelProgress) => {
+ console.log({progress, totalBytes, downloadedBytes});
};
```
## Return Value
-resolves with the message `Model loaded successfully` if the model has been successfully stored in the `indexedDB` storage of the browser.
+Returns an object with the following properties:
+
+- `alreadyDownloaded`: Whether the model has already been downloaded.
## See also
-- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/whisper-wasm/src/helpers.ts)
+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/whisper-wasm/src/download-whisper-model.ts)
- [`@remotion/whisper-wasm`](/docs/whisper-wasm)
- [`transcribe()`](/docs/whisper-wasm/transcribe)
diff --git a/packages/docs/docs/whisper-wasm/get-loaded-models.mdx b/packages/docs/docs/whisper-wasm/get-loaded-models.mdx
index 03532d98c9..99ad627e3a 100644
--- a/packages/docs/docs/whisper-wasm/get-loaded-models.mdx
+++ b/packages/docs/docs/whisper-wasm/get-loaded-models.mdx
@@ -4,6 +4,10 @@ title: getLoadedModels()
crumb: '@remotion/whisper-wasm'
---
+:::warning
+**Unstable API**: This package is experimental for the moment. As we test it, we might make a few changes to the API.
+:::
+
Returns an array of Whisper models that have already been downloaded and stored in the browser's IndexedDB storage.
## Return value
diff --git a/packages/docs/docs/whisper-wasm/index.mdx b/packages/docs/docs/whisper-wasm/index.mdx
index b736ab8606..be50bb9db5 100644
--- a/packages/docs/docs/whisper-wasm/index.mdx
+++ b/packages/docs/docs/whisper-wasm/index.mdx
@@ -7,7 +7,7 @@ import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
:::warning
-**Unstable API**: This package is experimental. The API may change in the future.
+**Unstable API**: This package is experimental for the moment. As we test it, we might make a few changes to the API.
:::
Similar to [@remotion/install-whisper-cpp](/docs/install-whisper-cpp) but for the browser. Allows you to transcribe audio locally in the browser, with the help of WASM.
@@ -22,70 +22,6 @@ import {TableOfContents} from './whisper-wasm';
This library is UI-agnostic and can be integrated with any frontend framework.
:::
-<Tabs defaultValue="react"
-values={[
-{ label: 'React', value: 'react' },
-{ label: 'Vanilla', value: 'html' },
-]}
->
-
-<TabItem value='react'>
-
-```tsx twoslash
-import {useState} from 'react';
-import {transcribe, canUseWhisperWasm, resampleTo16Khz, downloadWhisperModel, type WhisperWasmModel} from '@remotion/whisper-wasm';
-
-export default function MyApp() {
- const [text, setText] = useState<string | null>(null);
-
- const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
- const file = event.target.files?.[0];
- if (!file) return;
-
- setText('Processing...');
-
- const modelToUse: WhisperWasmModel = 'tiny.en';
-
- const {supported, detailedReason, reason} = await canUseWhisperWasm(modelToUse);
- if (!supported) {
- setText(`Whisper WASM is not supported in this environment: ${detailedReason}`);
- return;
- }
-
- setText('Downloading model...');
- await downloadWhisperModel({
- model: modelToUse,
- onProgress: (p) => setText(`Downloading model (${Math.round(p * 100)}%)...`),
- });
-
- setText('Resampling audio...');
- const channelWaveform = await resampleTo16Khz({
- file,
- onProgress: (p) => setText(`Resampling audio (${Math.round(p * 100)}%)...`),
- });
-
- setText('Transcribing...');
- const {transcription} = await transcribe({
- channelWaveform,
- model: modelToUse,
- onProgress: (p) => setText(`Transcribing (${Math.round(p * 100)}%)...`),
- });
- setText(transcription.map((t) => t.text).join(' '));
- };
-
- return (
- <div>
- <input type="file" accept="audio/*" onChange={handleFileChange} />
- {text && <p>{text}</p>}
- </div>
- );
-}
-```
-
-</TabItem>
-
-<TabItem value="html">
-
```tsx twoslash
import {transcribe, canUseWhisperWasm, resampleTo16Khz, downloadWhisperModel} from '@remotion/whisper-wasm';
@@ -94,48 +30,43 @@ import {transcribe, canUseWhisperWasm, resampleTo16Khz, downloadWhisperModel} fr
// <p id="status"></p>
const input = document.getElementById('audio-input') as HTMLInputElement;
-const status = document.getElementById('status') as HTMLParagraphElement;
input.addEventListener('change', async (e) => {
const file = input.files?.[0];
if (!file) return;
- status.textContent = 'Processing...';
+ console.log('Processing...');
const modelToUse = 'tiny.en';
const {supported, detailedReason} = await canUseWhisperWasm(modelToUse);
if (!supported) {
- status.textContent = `Whisper WASM is not supported in this environment: ${detailedReason}`;
- return;
+ throw new Error(`Whisper WASM is not supported in this environment: ${detailedReason}`);
}
- status.textContent = 'Downloading model...';
+ console.log('Downloading model...');
await downloadWhisperModel({
model: modelToUse,
- onProgress: (p) => (status.textContent = `Downloading model (${Math.round(p * 100)}%)...`),
+ onProgress: (p) => console.log(`Downloading model (${Math.round(p * 100)}%)...`),
});
- status.textContent = 'Resampling audio...';
+ console.log('Resampling audio...');
const channelWaveform = await resampleTo16Khz({
file,
- onProgress: (p) => (status.textContent = `Resampling audio (${Math.round(p * 100)}%)...`),
+ onProgress: (p) => console.log(`Resampling audio (${Math.round(p * 100)}%)...`),
});
- status.textContent = 'Transcribing...';
+ console.log('Transcribing...');
const {transcription} = await transcribe({
channelWaveform,
model: modelToUse,
- onProgress: (p) => (status.textContent = `Transcribing (${Math.round(p * 100)}%)...`),
+ onProgress: (p) => console.log(`Transcribing (${Math.round(p * 100)}%)...`),
});
- status.textContent = transcription.map((t) => t.text).join(' ');
+
+ console.log(transcription.map((t) => t.text).join(' '));
});
```
-</TabItem>
-
-</Tabs>
-
## Functions
<TableOfContents />
diff --git a/packages/docs/docs/whisper-wasm/resample-to-16khz.mdx b/packages/docs/docs/whisper-wasm/resample-to-16khz.mdx
index f728b9b744..b097022612 100644
--- a/packages/docs/docs/whisper-wasm/resample-to-16khz.mdx
+++ b/packages/docs/docs/whisper-wasm/resample-to-16khz.mdx
@@ -4,6 +4,10 @@ title: resampleTo16Khz()
crumb: '@remotion/whisper-wasm'
---
+:::warning
+**Unstable API**: This package is experimental for the moment. As we test it, we might make a few changes to the API.
+:::
+
# resampleTo16Khz()
Processes an audio `File` or `Blob` by decoding it, converting it to mono, and resampling it to a 16kHz `Float32Array`. This prepares the audio data for use with the [`transcribe()`](/docs/whisper-wasm/transcribe) function.
diff --git a/packages/docs/docs/whisper-wasm/transcribe.mdx b/packages/docs/docs/whisper-wasm/transcribe.mdx
index b0e8c5cd7a..9e8a9ad8ec 100644
--- a/packages/docs/docs/whisper-wasm/transcribe.mdx
+++ b/packages/docs/docs/whisper-wasm/transcribe.mdx
@@ -3,6 +3,10 @@ title: transcribe()
crumb: '@remotion/whisper-wasm'
---
+:::warning
+**Unstable API**: This package is experimental for the moment. As we test it, we might make a few changes to the API.
+:::
+
# transcribe()
Transcribes pre-processed audio data (a `Float32Array` waveform) using WebAssembly-compiled `whisper.cpp`, returning the transcription. To transcribe an audio file, you first need to process it using [`resampleTo16Khz()`](/docs/whisper-wasm/resample-to-16khz).
diff --git a/packages/whisper-wasm/src/download-model.ts b/packages/whisper-wasm/src/download-model.ts
index e1397dfcc7..2693c59223 100644
--- a/packages/whisper-wasm/src/download-model.ts
+++ b/packages/whisper-wasm/src/download-model.ts
@@ -1,9 +1,11 @@
export const fetchRemote = async ({
url,
onProgress,
+ expectedLength,
}: {
url: string;
onProgress: (progress: number) => void;
+ expectedLength: number;
}) => {
// start the fetch
const response = await fetch(url, {method: 'get'});
@@ -14,11 +16,16 @@ export const fetchRemote = async ({
const contentLength = response.headers.get('content-length') as string;
// hugging face servers do include this header
const total = parseInt(contentLength, 10);
+ if (total !== expectedLength) {
+ throw new Error(
+ `Content-Length header is ${total} for ${url} but expected ${expectedLength}`,
+ );
+ }
+
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let receivedLength = 0;
- let progressLast = -1;
while (true) {
const {done, value} = await reader.read();
@@ -30,15 +37,7 @@ export const fetchRemote = async ({
chunks.push(value);
receivedLength += value.length;
- if (contentLength) {
- const progressPercentage = receivedLength / total;
- onProgress(progressPercentage);
-
- const progressCur = Math.round((receivedLength / total) * 10);
- if (progressCur !== progressLast) {
- progressLast = progressCur;
- }
- }
+ onProgress(receivedLength);
}
let position = 0;
diff --git a/packages/whisper-wasm/src/download-whisper-model.ts b/packages/whisper-wasm/src/download-whisper-model.ts
index 360c6116c4..6ee93d00a3 100644
--- a/packages/whisper-wasm/src/download-whisper-model.ts
+++ b/packages/whisper-wasm/src/download-whisper-model.ts
@@ -1,13 +1,23 @@
import {canUseWhisperWasm} from './can-use-whisper-wasm';
-import {MODELS, type WhisperWasmModel} from './constants';
+import {MODELS, SIZES, type WhisperWasmModel} from './constants';
import {getObject} from './db/get-object-from-db';
import {putObject} from './db/put-object';
import {fetchRemote} from './download-model';
import {getModelUrl} from './get-model-url';
+export type DownloadWhisperModelProgress = {
+ downloadedBytes: number;
+ totalBytes: number;
+ progress: number;
+};
+
+export type DownloadWhisperModelOnProgress = (
+ progress: DownloadWhisperModelProgress,
+) => void;
+
export interface DownloadWhisperModelParams {
model: WhisperWasmModel;
- onProgress: (progress: number) => void;
+ onProgress: DownloadWhisperModelOnProgress;
}
export type DownloadWhisperModelResult = {
@@ -29,22 +39,45 @@ export const downloadWhisperModel = async ({
if (!usabilityCheck.supported) {
return Promise.reject(
new Error(
- `Whisper Wasm is not supported in this environment. Reason: ${usabilityCheck.detailedReason}`,
+ `Whisper.wasm is not supported in this environment. Reason: ${usabilityCheck.detailedReason}`,
),
);
}
const url = getModelUrl(model);
+ const modelSize = SIZES[model];
const existingModel = await getObject({key: url});
if (existingModel) {
- onProgress(1);
+ onProgress({
+ downloadedBytes: modelSize,
+ totalBytes: modelSize,
+ progress: 1,
+ });
+
return {
alreadyDownloaded: true,
};
}
- const data = await fetchRemote({url, onProgress});
+ const data = await fetchRemote({
+ url,
+ onProgress: (bytes) => {
+ onProgress({
+ downloadedBytes: bytes,
+ progress: bytes / modelSize,
+ totalBytes: modelSize,
+ });
+ },
+ expectedLength: modelSize,
+ });
+
+ onProgress({
+ downloadedBytes: modelSize,
+ totalBytes: modelSize,
+ progress: 1,
+ });
+
await putObject({key: url, value: data});
return {
diff --git a/packages/whisper-wasm/src/index.ts b/packages/whisper-wasm/src/index.ts
index c1390d594b..1b943eb86f 100644
--- a/packages/whisper-wasm/src/index.ts
+++ b/packages/whisper-wasm/src/index.ts
@@ -6,7 +6,9 @@ import type {
import type {WhisperWasmLanguage, WhisperWasmModel} from './constants';
import type {deleteModel as originalDeleteModel} from './delete-model';
import type {
+ DownloadWhisperModelOnProgress,
DownloadWhisperModelParams,
+ DownloadWhisperModelProgress,
DownloadWhisperModelResult,
downloadWhisperModel as originalDownloadWhisperModel,
} from './download-whisper-model';
@@ -58,7 +60,9 @@ export const resampleTo16Khz: typeof originalResampleTo16Khz = () => {
export type {
CanUseWhisperWasmResult,
+ DownloadWhisperModelOnProgress,
DownloadWhisperModelParams,
+ DownloadWhisperModelProgress,
DownloadWhisperModelResult,
ResampleTo16KhzParams,
TranscribeParams,