🎥 Make videos programmatically with React
a single `canUseWhisperWasm` API for usability checks
Igor Samokhovetsf7d633cbc9f5
diff --git a/packages/example/src/WhisperWasm/index.tsx b/packages/example/src/WhisperWasm/index.tsxindex 85eae122f8..0c887b1d49 100644--- a/packages/example/src/WhisperWasm/index.tsx+++ b/packages/example/src/WhisperWasm/index.tsx@@ -1,10 +1,10 @@import {+ type WhisperWasmModel,deleteModel,downloadWhisperModel,getLoadedModels,transcribe,} from '@remotion/whisper-wasm';-import {WhisperModel} from '@remotion/whisper-wasm/src/constants';import {useCallback, useEffect, useState} from 'react';import {staticFile} from 'remotion';@@ -13,7 +13,7 @@ const audioFileUrl = staticFile('16khz.wav');const model = 'base';export const WhisperWasm = () => {- const [loadedModels, setLoadedModels] = useState<WhisperModel[]>([]);+ const [loadedModels, setLoadedModels] = useState<WhisperWasmModel[]>([]);const fetchModels = useCallback(async () => {const models = await getLoadedModels();@@ -35,7 +35,7 @@ export const WhisperWasm = () => {const onClickTranscribe = useCallback(async () => {const file = await fetch(audioFileUrl);const blob = await file.blob();- const transcription = await transcribe({+ const {transcription} = await transcribe({model,file: blob,logLevel: 'verbose',diff --git a/packages/whisper-wasm/src/can-download-model.ts b/packages/whisper-wasm/src/can-download-model.tsdeleted file mode 100644index 6be2a5cf61..0000000000--- a/packages/whisper-wasm/src/can-download-model.ts+++ /dev/null@@ -1,61 +0,0 @@-import type {WhisperModel} from './constants';-import {MODELS, SIZES} from './constants';--export interface CanDownloadModelResult {- canDownload: boolean;- reason?: string;-}--export const canDownloadModel = async (- model: WhisperModel,-): Promise<CanDownloadModelResult> => {- if (typeof window === 'undefined' || !window.navigator?.storage?.estimate) {- return {- canDownload: false,- reason: 'Storage estimation API is not available in this environment.',- };- }-- if (!model || !MODELS.includes(model)) {- return {- canDownload: false,- reason: `Invalid model name. Supported models: ${MODELS.join(', ')}.`,- };- }-- try {- const estimate = await navigator.storage.estimate();-- if (estimate.quota === undefined) {- return {- canDownload: false,- reason: 'navigator.storage.estimate() API returned undefined quota.',- };- }-- if (estimate.usage === undefined) {- return {- canDownload: false,- reason: 'navigator.storage.estimate() API returned undefined usage.',- };- }-- const remaining = estimate.quota - estimate.usage;- const modelSize = SIZES[model];-- if (remaining < modelSize) {- return {- canDownload: false,- reason: `Not enough space to download the model. Required: ${modelSize} bytes, Available: ${remaining} bytes.`,- };- }-- return {canDownload: true};- } catch (error) {- const errorMessage = error instanceof Error ? error.message : String(error);- return {- canDownload: false,- reason: `Error estimating storage: ${errorMessage}`,- };- }-};diff --git a/packages/whisper-wasm/src/can-use-whisper-wasm.ts b/packages/whisper-wasm/src/can-use-whisper-wasm.tsindex 7f6267b37f..ab38dbbf45 100644--- a/packages/whisper-wasm/src/can-use-whisper-wasm.ts+++ b/packages/whisper-wasm/src/can-use-whisper-wasm.ts@@ -1,29 +1,104 @@+import type {WhisperWasmModel} from './constants';+import {MODELS, SIZES} from './constants';++export enum WhisperWasmUnsupportedReason {+ WindowUndefined = 'window-undefined',+ IndexedDbUnavailable = 'indexed-db-unavailable',+ NavigatorStorageUnavailable = 'navigator-storage-unavailable',+ StorageEstimationApiUnavailable = 'storage-estimation-api-unavailable',+ InvalidModelName = 'invalid-model-name',+ QuotaUndefined = 'quota-undefined',+ UsageUndefined = 'usage-undefined',+ NotEnoughSpace = 'not-enough-space',+ ErrorEstimatingStorage = 'error-estimating-storage',+}+export interface CanUseWhisperWasmResult {supported: boolean;- reasons: string[];+ reason?: WhisperWasmUnsupportedReason;+ detailedReason?: string;}-export const canUseWhisperWasm = (): CanUseWhisperWasmResult => {- const reasons: string[] = [];-+export const canUseWhisperWasm = async (+ model: WhisperWasmModel,+): Promise<CanUseWhisperWasmResult> => {if (typeof window === 'undefined') {- reasons.push(- '`window` is not defined. This module can only be used in a browser environment.',- );+ return {+ supported: false,+ reason: WhisperWasmUnsupportedReason.WindowUndefined,+ detailedReason:+ '`window` is not defined. This module can only be used in a browser environment.',+ };}- if (!window?.indexedDB) {- reasons.push('IndexedDB is not available in this environment.');+ if (!window.indexedDB) {+ return {+ supported: false,+ reason: WhisperWasmUnsupportedReason.IndexedDbUnavailable,+ detailedReason: 'IndexedDB is not available in this environment.',+ };}if (!navigator?.storage || !navigator?.storage.estimate) {- reasons.push(- '`navigator.storage.estimate()` API is not available in this environment.',- );+ return {+ supported: false,+ reason: WhisperWasmUnsupportedReason.NavigatorStorageUnavailable,+ detailedReason:+ '`navigator.storage.estimate()` API is not available in this environment.',+ };+ }++ if (!model || !MODELS.includes(model)) {+ return {+ supported: false,+ reason: WhisperWasmUnsupportedReason.InvalidModelName,+ detailedReason: `Invalid model name. Supported models: ${MODELS.join(+ ', ',+ )}.`,+ };+ }++ try {+ const estimate = await navigator.storage.estimate();++ if (estimate.quota === undefined) {+ return {+ supported: false,+ reason: WhisperWasmUnsupportedReason.QuotaUndefined,+ detailedReason:+ 'navigator.storage.estimate() API returned undefined quota.',+ };+ }++ if (estimate.usage === undefined) {+ return {+ supported: false,+ reason: WhisperWasmUnsupportedReason.UsageUndefined,+ detailedReason:+ 'navigator.storage.estimate() API returned undefined usage.',+ };+ }++ const remaining = estimate.quota - estimate.usage;+ const modelSize = SIZES[model];++ if (remaining < modelSize) {+ return {+ supported: false,+ reason: WhisperWasmUnsupportedReason.NotEnoughSpace,+ detailedReason: `Not enough space to download the model. Required: ${modelSize} bytes, Available: ${remaining} bytes.`,+ };+ }+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ return {+ supported: false,+ reason: WhisperWasmUnsupportedReason.ErrorEstimatingStorage,+ detailedReason: `Error estimating storage: ${errorMessage}`,+ };}return {- supported: reasons.length === 0,- reasons,+ supported: true,};};diff --git a/packages/whisper-wasm/src/constants.ts b/packages/whisper-wasm/src/constants.tsindex eae4c5d581..8c895f9163 100644--- a/packages/whisper-wasm/src/constants.ts+++ b/packages/whisper-wasm/src/constants.ts@@ -11,7 +11,7 @@ export const MODELS = ['small.en',] as const;-export type WhisperModel = (typeof MODELS)[number];+export type WhisperWasmModel = (typeof MODELS)[number];export const LANGUAGES = [// whisper allows passing 'auto' to auto-detect the language@@ -220,9 +220,9 @@ export const LANGUAGES = ['cantonese',] as const;-export type WhisperLanguage = (typeof LANGUAGES)[number];+export type WhisperWasmLanguage = (typeof LANGUAGES)[number];-export const SIZES: {[key in WhisperModel]: number} = {+export const SIZES: {[key in WhisperWasmModel]: number} = {tiny: 77691713,'tiny.en': 77704715,base: 147951465,diff --git a/packages/whisper-wasm/src/delete-model.ts b/packages/whisper-wasm/src/delete-model.tsindex 47cca9d98d..219daa9aa7 100644--- a/packages/whisper-wasm/src/delete-model.ts+++ b/packages/whisper-wasm/src/delete-model.ts@@ -1,8 +1,8 @@-import type {WhisperModel} from './constants';+import type {WhisperWasmModel} from './constants';import {deleteObject} from './db/delete-object';import {getModelUrl} from './get-model-url';-export const deleteModel = async (model: WhisperModel) => {+export const deleteModel = async (model: WhisperWasmModel) => {const url = getModelUrl(model);await deleteObject({key: url});};diff --git a/packages/whisper-wasm/src/download-whisper-model.ts b/packages/whisper-wasm/src/download-whisper-model.tsindex 22bdbc7d81..84db29286c 100644--- a/packages/whisper-wasm/src/download-whisper-model.ts+++ b/packages/whisper-wasm/src/download-whisper-model.ts@@ -1,14 +1,12 @@-import {canDownloadModel} from './can-download-model';import {canUseWhisperWasm} from './can-use-whisper-wasm';-import type {WhisperModel} from './constants';-import {MODELS} from './constants';+import 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 interface DownloadWhisperModelParams {- model: WhisperModel;+ model: WhisperWasmModel;onProgress: (progress: number) => void;}@@ -20,24 +18,16 @@ export const downloadWhisperModel = async ({model,onProgress,}: DownloadWhisperModelParams): Promise<DownloadWhisperModelResult> => {- const usabilityCheck = canUseWhisperWasm();+ const usabilityCheck = await canUseWhisperWasm(model);if (!usabilityCheck.supported) {return Promise.reject(new Error(- `Whisper Wasm is not supported in this environment. Reasons: ${usabilityCheck.reasons.join(- ', ',- )}`,+ `Whisper Wasm is not supported in this environment. Reason: ${usabilityCheck.detailedReason}`,),);}- if (!model || !MODELS.includes(model)) {- return Promise.reject(- new Error(`Invalid model name. Supported models: ${MODELS.join(', ')}.`),- );- }-const url = getModelUrl(model);const existingModel = await getObject({key: url});@@ -48,12 +38,6 @@ export const downloadWhisperModel = async ({};}- const downloadCheck = await canDownloadModel(model);-- if (!downloadCheck.canDownload) {- return Promise.reject(new Error(downloadCheck.reason));- }-const data = await fetchRemote({url, onProgress});await putObject({key: url, value: data});diff --git a/packages/whisper-wasm/src/get-loaded-models.ts b/packages/whisper-wasm/src/get-loaded-models.tsindex 40c8e83eb3..ce45a2ffe6 100644--- a/packages/whisper-wasm/src/get-loaded-models.ts+++ b/packages/whisper-wasm/src/get-loaded-models.ts@@ -1,12 +1,12 @@-import type {WhisperModel} from './constants';+import type {WhisperWasmModel} from './constants';import {MODELS} from './constants';import {getKeysFromObjectStore} from './db/get-object-from-db';import {openDb} from './db/open-db';import {getModelUrl} from './get-model-url';-export const getLoadedModels = async (): Promise<WhisperModel[]> => {+export const getLoadedModels = async (): Promise<WhisperWasmModel[]> => {const objectStore = await openDb('readonly');- const loadedModels: WhisperModel[] = [];+ const loadedModels: WhisperWasmModel[] = [];const result = await getKeysFromObjectStore({objectStore,diff --git a/packages/whisper-wasm/src/get-model-url.ts b/packages/whisper-wasm/src/get-model-url.tsindex bedc4fde52..ffd818aa4a 100644--- a/packages/whisper-wasm/src/get-model-url.ts+++ b/packages/whisper-wasm/src/get-model-url.ts@@ -1,6 +1,6 @@-import type {WhisperModel} from './constants';+import type {WhisperWasmModel} from './constants';-export const getModelUrl = (model: WhisperModel) => {+export const getModelUrl = (model: WhisperWasmModel) => {return `https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-${model}.bin`;};diff --git a/packages/whisper-wasm/src/index.ts b/packages/whisper-wasm/src/index.tsindex 2511f1a258..074f5df8c2 100644--- a/packages/whisper-wasm/src/index.ts+++ b/packages/whisper-wasm/src/index.ts@@ -1,11 +1,9 @@-import type {- CanDownloadModelResult,- canDownloadModel as originalCanDownloadModel,-} from './can-download-model';import type {CanUseWhisperWasmResult,canUseWhisperWasm as originalCanUseWhisperWasm,+ WhisperWasmUnsupportedReason,} from './can-use-whisper-wasm';+import type {WhisperWasmLanguage, WhisperWasmModel} from './constants';import type {deleteModel as originalDeleteModel} from './delete-model';import type {DownloadWhisperModelParams,@@ -48,16 +46,12 @@ export const canUseWhisperWasm: typeof originalCanUseWhisperWasm = () => {);};-export const canDownloadModel: typeof originalCanDownloadModel = () => {- throw new Error(- 'Loading this module from CommonJS is not supported. Load the ESM version of @remotion/whisper-wasm.',- );-};-export type {- CanDownloadModelResult,CanUseWhisperWasmResult,DownloadWhisperModelParams,DownloadWhisperModelResult,TranscribeParams,+ WhisperWasmLanguage,+ WhisperWasmModel,+ WhisperWasmUnsupportedReason,};diff --git a/packages/whisper-wasm/src/transcribe.ts b/packages/whisper-wasm/src/transcribe.tsindex 98d0e7472d..28c87ab9b8 100644--- a/packages/whisper-wasm/src/transcribe.ts+++ b/packages/whisper-wasm/src/transcribe.ts@@ -2,7 +2,7 @@import type {MainModule} from '../main';import {checkForHeaders} from './check-for-headers';-import type {WhisperLanguage, WhisperModel} from './constants';+import type {WhisperWasmLanguage, WhisperWasmModel} from './constants';import {getObject} from './db/get-object-from-db';import {getModelUrl} from './get-model-url';import {loadMod} from './load-mod/load-mod';@@ -104,8 +104,8 @@ const audioProcessor = (file: Blob) => {export type TranscribeParams = {file: Blob;- model: WhisperModel;- language?: WhisperLanguage;+ model: WhisperWasmModel;+ language?: WhisperWasmLanguage;onProgress?: (p: number) => void;onTranscribedChunks?: (transcription: TranscriptionItemWithTimestamp[],