🎥 Make videos programmatically with React
Manage cached transcription models
JonnyBurger3b70f0e07d9c
diff --git a/packages/docs/docs/whisper-webgpu/dispose-whisper-model.mdx b/packages/docs/docs/whisper-webgpu/dispose-whisper-model.mdxindex c65bc6cf42..9ddea4e6b5 100644--- a/packages/docs/docs/whisper-webgpu/dispose-whisper-model.mdx+++ b/packages/docs/docs/whisper-webgpu/dispose-whisper-model.mdx@@ -27,3 +27,4 @@ Only dispose this model. Default: all loaded models.## See also- [`loadWhisperModel()`](/docs/whisper-webgpu/load-whisper-model)+- [`removeWhisperModel()`](/docs/whisper-webgpu/remove-whisper-model)diff --git a/packages/docs/docs/whisper-webgpu/is-whisper-model-cached.mdx b/packages/docs/docs/whisper-webgpu/is-whisper-model-cached.mdxindex e46ca71f77..835704d66c 100644--- a/packages/docs/docs/whisper-webgpu/is-whisper-model-cached.mdx+++ b/packages/docs/docs/whisper-webgpu/is-whisper-model-cached.mdx@@ -36,3 +36,4 @@ Models cached from Hugging Face by versions before 4.0.522 do not satisfy this c- [`getAvailableModels()`](/docs/whisper-webgpu/get-available-models)- [`loadWhisperModel()`](/docs/whisper-webgpu/load-whisper-model)+- [`removeWhisperModel()`](/docs/whisper-webgpu/remove-whisper-model)diff --git a/packages/docs/docs/whisper-webgpu/load-whisper-model.mdx b/packages/docs/docs/whisper-webgpu/load-whisper-model.mdxindex 30908f3c34..b99a7eaf08 100644--- a/packages/docs/docs/whisper-webgpu/load-whisper-model.mdx+++ b/packages/docs/docs/whisper-webgpu/load-whisper-model.mdx@@ -47,4 +47,5 @@ Versions before 4.0.522 downloaded models from Hugging Face. A model cached by a- [`disposeWhisperModel()`](/docs/whisper-webgpu/dispose-whisper-model)- [`isWhisperModelCached()`](/docs/whisper-webgpu/is-whisper-model-cached)+- [`removeWhisperModel()`](/docs/whisper-webgpu/remove-whisper-model)- [`transcribe()`](/docs/whisper-webgpu/transcribe)diff --git a/packages/docs/docs/whisper-webgpu/remove-whisper-model.mdx b/packages/docs/docs/whisper-webgpu/remove-whisper-model.mdxnew file mode 100644index 0000000000..bd06eafe2b--- /dev/null+++ b/packages/docs/docs/whisper-webgpu/remove-whisper-model.mdx@@ -0,0 +1,33 @@+---+image: /generated/articles-docs-whisper-webgpu-remove-whisper-model.png+title: removeWhisperModel()+crumb: '@remotion/whisper-webgpu'+---++# removeWhisperModel()<AvailableFrom v="4.0.523" />++Removes a Whisper model from memory and the persistent browser cache.++If the model is still loading or transcribing, removal waits for the operation to finish.++```ts twoslash title="remove-model.ts"+import {removeWhisperModel} from '@remotion/whisper-webgpu';++await removeWhisperModel({model: 'small.en'});+```++## Options++### model++One of the names returned by [`getAvailableModels()`](/docs/whisper-webgpu/get-available-models).++## Compatibility++<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering player studio hideServers />++## See also++- [`disposeWhisperModel()`](/docs/whisper-webgpu/dispose-whisper-model)+- [`isWhisperModelCached()`](/docs/whisper-webgpu/is-whisper-model-cached)+- [`loadWhisperModel()`](/docs/whisper-webgpu/load-whisper-model)diff --git a/packages/docs/docs/whisper-webgpu/table-of-contents.tsx b/packages/docs/docs/whisper-webgpu/table-of-contents.tsxindex a451665fa7..5baa367f2d 100644--- a/packages/docs/docs/whisper-webgpu/table-of-contents.tsx+++ b/packages/docs/docs/whisper-webgpu/table-of-contents.tsx@@ -25,6 +25,10 @@ export const TableOfContents: React.FC = () => {<strong>loadWhisperModel()</strong><div>Download and initialize a model</div></TOCItem>+ <TOCItem link="/docs/whisper-webgpu/remove-whisper-model">+ <strong>removeWhisperModel()</strong>+ <div>Remove a model from the browser cache</div>+ </TOCItem><TOCItem link="/docs/whisper-webgpu/transcribe"><strong>transcribe()</strong><div>Transcribe a waveform with word-level timestamps</div>diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 057e3f9a98..0c9b9b6d18 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -996,6 +996,7 @@ const sidebars: SidebarsConfig = {'whisper-webgpu/clear-stale-models','whisper-webgpu/is-whisper-model-cached','whisper-webgpu/load-whisper-model',+ 'whisper-webgpu/remove-whisper-model','whisper-webgpu/transcribe','whisper-webgpu/to-captions','whisper-webgpu/resample-to-16khz',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex 764fcff55d..1527f79353 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -9101,6 +9101,15 @@ export const articles = [noAi: false,slug: 'whisper-webgpu/load-whisper-model',},+ {+ id: 'whisper-webgpu/remove-whisper-model',+ title: 'removeWhisperModel()',+ relativePath: 'docs/whisper-webgpu/remove-whisper-model.mdx',+ compId: 'articles-docs-whisper-webgpu-remove-whisper-model',+ crumb: '@remotion/whisper-webgpu',+ noAi: false,+ slug: 'whisper-webgpu/remove-whisper-model',+ },{id: 'whisper-webgpu/resample-to-16khz',title: 'resampleTo16Khz()',diff --git a/packages/docs/static/generated/articles-docs-whisper-webgpu-remove-whisper-model.png b/packages/docs/static/generated/articles-docs-whisper-webgpu-remove-whisper-model.pngnew file mode 100644index 0000000000..b5d3dcffa5Binary files /dev/null and b/packages/docs/static/generated/articles-docs-whisper-webgpu-remove-whisper-model.png differdiff --git a/packages/example/e2e/transcription-modal.test.mts b/packages/example/e2e/transcription-modal.test.mtsindex 1822418d2a..266039238b 100644--- a/packages/example/e2e/transcription-modal.test.mts+++ b/packages/example/e2e/transcription-modal.test.mts@@ -62,13 +62,17 @@ test.describe('transcription modal', () => {await dialog.getByRole('button', {name: 'Models', exact: true}).click();await expect(dialog.getByText(- 'Models are downloaded in the background when a transcription job starts. Follow the download progress in Jobs.',+ 'Models are downloaded automatically when a transcription starts. You can also manage the browser cache here.',{exact: true},),).toBeVisible();+ await expect(dialog.getByText(/^Select/)).toHaveCount(0);+ await expect(+ dialog.getByRole('button', {name: 'Download tiny', exact: true}),+ ).toBeVisible();await expect(dialog.getByText('Output in public/', {exact: true}),- ).toHaveCount(0);+ ).not.toBeVisible();await dialog.getByRole('button', {name: 'Transcribe', exact: true}).last()diff --git a/packages/studio/src/components/Transcription/Models.tsx b/packages/studio/src/components/Transcription/Models.tsxnew file mode 100644index 0000000000..6ec3bc4e18--- /dev/null+++ b/packages/studio/src/components/Transcription/Models.tsx@@ -0,0 +1,325 @@+import {formatBytes} from '@remotion/studio-shared';+import {+ clearStaleModels,+ getAvailableModels,+ isWhisperModelCached,+ loadWhisperModel,+ removeWhisperModel,+ type WhisperWebGpuModel,+ type WhisperWebGpuModelLoadProgress,+} from '@remotion/whisper-webgpu';+import React, {useCallback, useEffect, useRef, useState} from 'react';+import {+ BLUE,+ BORDER_WHITE_ALPHA_12,+ LIGHT_TEXT,+ WHITE,+} from '../../helpers/colors';+import {CheckCircleFilled} from '../../icons/check-circle-filled';+import {CloudDownloadIcon} from '../../icons/cloud-download';+import {Minus} from '../../icons/minus';+import {TrashIcon} from '../../icons/trash';+import type {RenderInlineAction} from '../InlineAction';+import {InlineAction} from '../InlineAction';+import {VERTICAL_SCROLLBAR_CLASSNAME} from '../Menu/is-menu-item';+import {ValidationMessage} from '../NewComposition/ValidationMessage';+import {optionsPanel} from '../RenderModal/render-modals';+import {Spinner} from '../Spinner';++const AVAILABLE_MODELS = getAvailableModels();++const modelPanel: React.CSSProperties = {+ ...optionsPanel,+ flexDirection: 'column',+};++const hiddenPanel: React.CSSProperties = {+ display: 'none',+};++const container: React.CSSProperties = {+ alignSelf: 'flex-start',+ boxSizing: 'border-box',+ flex: 1,+ fontFamily: 'sans-serif',+ minWidth: 0,+ padding: '16px 16px 0',+};++const description: React.CSSProperties = {+ color: LIGHT_TEXT,+ fontSize: 13,+ lineHeight: 1.5,+ margin: 0,+};++const list: React.CSSProperties = {+ marginTop: 14,+};++const modelRow: React.CSSProperties = {+ alignItems: 'center',+ borderBottom: BORDER_WHITE_ALPHA_12,+ display: 'flex',+ gap: 10,+ minHeight: 38,+ padding: '0 10px',+};++const lastModelRow: React.CSSProperties = {+ ...modelRow,+ borderBottom: 'none',+};++const statusIcon: React.CSSProperties = {+ flexShrink: 0,+ height: 14,+ width: 14,+};++const modelName: React.CSSProperties = {+ color: WHITE,+ flex: 1,+ fontFamily: 'monospace',+ fontSize: 13,+ lineHeight: 1.4,+ minWidth: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+};++const status: React.CSSProperties = {+ color: LIGHT_TEXT,+ fontSize: 12,+ fontVariantNumeric: 'tabular-nums',+ lineHeight: 1.4,+ whiteSpace: 'nowrap',+};++const actionIcon: React.CSSProperties = {+ height: 14,+ width: 14,+};++type ModelActionState =+ | {type: 'idle'}+ | {+ type: 'downloading';+ model: WhisperWebGpuModel;+ progress: WhisperWebGpuModelLoadProgress;+ }+ | {type: 'removing'; model: WhisperWebGpuModel}+ | {type: 'error'; model: WhisperWebGpuModel; message: string};++export const Models: React.FC<{readonly visible: boolean}> = ({visible}) => {+ const mounted = useRef(true);+ const initialized = useRef(false);+ const [cachedModels, setCachedModels] =+ useState<ReadonlySet<WhisperWebGpuModel> | null>(null);+ const [actionState, setActionState] = useState<ModelActionState>({+ type: 'idle',+ });+ const [cacheCheckError, setCacheCheckError] = useState<string | null>(null);++ useEffect(() => {+ return () => {+ mounted.current = false;+ };+ }, []);++ useEffect(() => {+ if (!visible || initialized.current) {+ return;+ }++ initialized.current = true;+ clearStaleModels()+ .then(() => {+ return Promise.all(+ AVAILABLE_MODELS.map(async ({name}) => {+ return (await isWhisperModelCached({model: name})) ? name : null;+ }),+ );+ })+ .then((models) => {+ if (mounted.current) {+ setCachedModels(+ new Set(+ models.filter(+ (model): model is WhisperWebGpuModel => model !== null,+ ),+ ),+ );+ }+ })+ .catch((error) => {+ if (mounted.current) {+ setCachedModels(new Set());+ setCacheCheckError(+ error instanceof Error ? error.message : String(error),+ );+ }+ });+ }, [visible]);++ const downloadModel = useCallback((model: WhisperWebGpuModel) => {+ setActionState({+ type: 'downloading',+ model,+ progress: {+ file: null,+ loadedBytes: 0,+ progress: 0,+ status: 'loading',+ totalBytes:+ AVAILABLE_MODELS.find(({name}) => name === model)+ ?.webGpuDownloadSize ?? null,+ },+ });+ loadWhisperModel({+ model,+ onProgress: (progress) => {+ if (mounted.current) {+ setActionState({type: 'downloading', model, progress});+ }+ },+ })+ .then(() => {+ if (mounted.current) {+ setCachedModels((current) => new Set([...(current ?? []), model]));+ setActionState({type: 'idle'});+ }+ })+ .catch((error) => {+ if (mounted.current) {+ setActionState({+ type: 'error',+ model,+ message: error instanceof Error ? error.message : String(error),+ });+ }+ });+ }, []);++ const removeModel = useCallback((model: WhisperWebGpuModel) => {+ setActionState({type: 'removing', model});+ removeWhisperModel({model})+ .then(() => {+ if (mounted.current) {+ setCachedModels((current) => {+ const next = new Set(current ?? []);+ next.delete(model);+ return next;+ });+ setActionState({type: 'idle'});+ }+ })+ .catch((error) => {+ if (mounted.current) {+ setActionState({+ type: 'error',+ model,+ message: error instanceof Error ? error.message : String(error),+ });+ }+ });+ }, []);++ const renderDownloadIcon: RenderInlineAction = useCallback((color) => {+ return <CloudDownloadIcon color={color} style={actionIcon} />;+ }, []);+ const renderRemoveIcon: RenderInlineAction = useCallback((color) => {+ return <TrashIcon color={color} style={actionIcon} />;+ }, []);+ const actionInProgress =+ actionState.type === 'downloading' || actionState.type === 'removing';++ return (+ <div+ style={visible ? modelPanel : hiddenPanel}+ className={VERTICAL_SCROLLBAR_CLASSNAME}+ >+ <div style={container}>+ <p style={description}>+ Models are downloaded automatically when a transcription starts. You+ can also manage the browser cache here.+ </p>+ {cacheCheckError ? (+ <ValidationMessage+ align="flex-start"+ message={cacheCheckError}+ type="error"+ />+ ) : null}+ <div style={list} role="list" aria-label="Whisper models">+ {AVAILABLE_MODELS.map((model, index) => {+ const cached = cachedModels?.has(model.name) ?? false;+ const processingThisModel =+ actionState.type !== 'idle' &&+ actionState.type !== 'error' &&+ actionState.model === model.name;+ const progress =+ actionState.type === 'downloading' &&+ actionState.model === model.name+ ? actionState.progress.progress+ : null;+ const modelStatus = processingThisModel+ ? actionState.type === 'removing'+ ? 'Removing…'+ : `Downloading${progress === null ? '…' : ` ${Math.round(progress * 100)}%`}`+ : actionState.type === 'error' && actionState.model === model.name+ ? actionState.message+ : cached+ ? `${formatBytes(model.webGpuDownloadSize)} · Downloaded`+ : formatBytes(model.webGpuDownloadSize);++ return (+ <div+ key={model.name}+ role="listitem"+ style={+ index === AVAILABLE_MODELS.length - 1+ ? lastModelRow+ : modelRow+ }+ >+ {cached ? (+ <CheckCircleFilled+ aria-hidden+ style={{...statusIcon, fill: BLUE}}+ />+ ) : (+ <Minus aria-hidden color={LIGHT_TEXT} style={statusIcon} />+ )}+ <span style={modelName}>{model.name}</span>+ <span style={status} title={modelStatus}>+ {modelStatus}+ </span>+ {processingThisModel ? (+ <Spinner duration={0.5} size={14} />+ ) : cached ? (+ <InlineAction+ disabled={actionInProgress}+ onClick={() => removeModel(model.name)}+ renderAction={renderRemoveIcon}+ title={`Remove ${model.name}`}+ variant={null}+ />+ ) : (+ <InlineAction+ disabled={cachedModels === null || actionInProgress}+ onClick={() => downloadModel(model.name)}+ renderAction={renderDownloadIcon}+ title={`Download ${model.name}`}+ variant={null}+ />+ )}+ </div>+ );+ })}+ </div>+ </div>+ </div>+ );+};diff --git a/packages/studio/src/components/Transcription/TranscriptionModal.tsx b/packages/studio/src/components/Transcription/TranscriptionModal.tsxindex 294ae1bf05..930bc3e75a 100644--- a/packages/studio/src/components/Transcription/TranscriptionModal.tsx+++ b/packages/studio/src/components/Transcription/TranscriptionModal.tsx@@ -61,6 +61,7 @@ import {getDefaultCaptionOutputName,validateCaptionOutputName,} from './caption-output-name';+import {Models} from './Models';import {WHISPER_LANGUAGES, type WhisperLanguage} from './whisper-languages';const TRANSCRIPTION_OUTPUT_MESSAGE_ID = 'remotion-transcription-output-message';@@ -142,38 +143,8 @@ const tooltipInlineCode: React.CSSProperties = {lineHeight: 'inherit',};-const modelsExplanation: React.CSSProperties = {- color: LIGHT_TEXT,- fontFamily: 'sans-serif',- fontSize: 13,- lineHeight: 1.5,- margin: 0,- padding: '0 16px 12px',-};--const modelName: React.CSSProperties = {- color: WHITE,- fontFamily: 'sans-serif',- fontSize: 14,- lineHeight: 1.5,-};--const modelDescription: React.CSSProperties = {- color: LIGHT_TEXT,- fontFamily: 'sans-serif',- fontSize: 12,- lineHeight: 1.5,-};--const modelAction: React.CSSProperties = {- display: 'flex',- alignItems: 'center',- gap: 12,-};--const modelSize: React.CSSProperties = {- ...modelDescription,- fontVariantNumeric: 'tabular-nums',+const hiddenPanel: React.CSSProperties = {+ display: 'none',};const existsMessageStyle: React.CSSProperties = {@@ -711,47 +682,6 @@ const AdvancedSettings: React.FC<{);};-const Models: React.FC<{- readonly selectedModel: WhisperWebGpuModel;- readonly setSelectedModel: (model: WhisperWebGpuModel) => void;-}> = ({selectedModel, setSelectedModel}) => {- return (- <div style={settingsPanel} className={VERTICAL_SCROLLBAR_CLASSNAME}>- <p style={modelsExplanation}>- Models are downloaded in the background when a transcription job starts.- Follow the download progress in Jobs.- </p>- {AVAILABLE_MODELS.map((model) => {- const selected = model.name === selectedModel;- return (- <div key={model.name} style={optionRow}>- <div>- <div style={modelName}>{model.name}</div>- <div style={modelDescription}>- {model.multilingual ? 'Multilingual' : 'English only'}- {model.supportsTranslation ? ' · Supports translation' : null}- </div>- </div>- <div style={modelAction}>- <div style={modelSize}>- {formatBytes(model.webGpuDownloadSize)}- </div>- <Button- onClick={() => setSelectedModel(model.name)}- disabled={selected}- size="compact"- style={selected ? undefined : buttonStyle}- >- {selected ? 'Selected' : 'Select'}- </Button>- </div>- </div>- );- })}- </div>- );-};-export const TranscriptionModal: React.FC<TranscriptionModalState> = ({audioStreamIndex,displayName,@@ -967,52 +897,49 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({Models</VerticalTab></div>- {tab === 'transcribe' ? (- <div style={settingsPanel} className={VERTICAL_SCROLLBAR_CLASSNAME}>- <OutputSettings- exists={exists}- onOutNameChange={onOutNameChange}- outName={outName}- validationMessage={outputValidationMessage}- />- <RenderModalHr />- <ModelSettings- selectedLanguage={selectedLanguage}- selectedModel={selectedModel}- selectedTask={selectedTask}- setSelectedLanguage={setSelectedLanguage}- setSelectedModel={setSelectedModel}- setSelectedTask={setSelectedTask}- supportState={supportState}- />- <RenderModalHr />- <AdvancedSettings- chunkLengthInSeconds={chunkLengthInSeconds}- decodingValidationMessage={decodingValidationMessage}- doSample={doSample}- forceFullSequences={forceFullSequences}- noRepeatNgramSize={noRepeatNgramSize}- repetitionPenalty={repetitionPenalty}- setChunkLengthInSeconds={setChunkLengthInSeconds}- setDoSample={setDoSample}- setForceFullSequences={setForceFullSequences}- setNoRepeatNgramSize={setNoRepeatNgramSize}- setRepetitionPenalty={setRepetitionPenalty}- setStrideLengthInSeconds={setStrideLengthInSeconds}- setTemperature={setTemperature}- setTopK={setTopK}- strideLengthInSeconds={strideLengthInSeconds}- temperature={temperature}- topK={topK}- validationMessage={chunkValidationMessage}- />- </div>- ) : (- <Models+ <div+ style={tab === 'transcribe' ? settingsPanel : hiddenPanel}+ className={VERTICAL_SCROLLBAR_CLASSNAME}+ >+ <OutputSettings+ exists={exists}+ onOutNameChange={onOutNameChange}+ outName={outName}+ validationMessage={outputValidationMessage}+ />+ <RenderModalHr />+ <ModelSettings+ selectedLanguage={selectedLanguage}selectedModel={selectedModel}+ selectedTask={selectedTask}+ setSelectedLanguage={setSelectedLanguage}setSelectedModel={setSelectedModel}+ setSelectedTask={setSelectedTask}+ supportState={supportState}/>- )}+ <RenderModalHr />+ <AdvancedSettings+ chunkLengthInSeconds={chunkLengthInSeconds}+ decodingValidationMessage={decodingValidationMessage}+ doSample={doSample}+ forceFullSequences={forceFullSequences}+ noRepeatNgramSize={noRepeatNgramSize}+ repetitionPenalty={repetitionPenalty}+ setChunkLengthInSeconds={setChunkLengthInSeconds}+ setDoSample={setDoSample}+ setForceFullSequences={setForceFullSequences}+ setNoRepeatNgramSize={setNoRepeatNgramSize}+ setRepetitionPenalty={setRepetitionPenalty}+ setStrideLengthInSeconds={setStrideLengthInSeconds}+ setTemperature={setTemperature}+ setTopK={setTopK}+ strideLengthInSeconds={strideLengthInSeconds}+ temperature={temperature}+ topK={topK}+ validationMessage={chunkValidationMessage}+ />+ </div>+ <Models visible={tab === 'models'} /></div></div></DismissableModal>diff --git a/packages/studio/src/test/caption-queue-processor.test.tsx b/packages/studio/src/test/caption-queue-processor.test.tsxindex e18247da6d..6355230998 100644--- a/packages/studio/src/test/caption-queue-processor.test.tsx+++ b/packages/studio/src/test/caption-queue-processor.test.tsx@@ -117,6 +117,7 @@ mock.module('@remotion/whisper-webgpu', () => ({});return {alreadyLoaded: false};},+ removeWhisperModel: () => Promise.resolve(),toCaptions: () => ({captions: [{diff --git a/packages/studio/src/test/transcription-modal.test.tsx b/packages/studio/src/test/transcription-modal.test.tsxindex 5c3cf5a971..95e940149a 100644--- a/packages/studio/src/test/transcription-modal.test.tsx+++ b/packages/studio/src/test/transcription-modal.test.tsx@@ -154,16 +154,10 @@ test('serializes transcription modal settings into caption jobs', async () => {screen.getByRole('dialog', {name: 'Transcribe interview.wav',});- const [submit, transcribeTab] = screen.getAllByRole('button', {+ const [submit] = screen.getAllByRole('button', {name: /^Transcribe$/,}) as HTMLButtonElement[];await waitFor(() => expect(submit.disabled).toBe(false));- fireEvent.click(screen.getByRole('button', {name: 'Models'}));- screen.getByText(- 'Models are downloaded in the background when a transcription job starts. Follow the download progress in Jobs.',- );- expect(screen.queryByText('Output in public/')).toBeNull();- fireEvent.click(transcribeTab);expect(screen.queryByText('Runs locally as a background job using WebGPU'),).toBeNull();diff --git a/packages/whisper-webgpu/src/index.ts b/packages/whisper-webgpu/src/index.tsindex 49b9910d8a..3fdc37b3ea 100644--- a/packages/whisper-webgpu/src/index.ts+++ b/packages/whisper-webgpu/src/index.ts@@ -1,9 +1,11 @@export {- canUseWhisperWebGpu,WhisperWebGpuUnsupportedReason,+ canUseWhisperWebGpu,} from './can-use-whisper-webgpu';export type {CanUseWhisperWebGpuResult} from './can-use-whisper-webgpu';export {clearStaleModels} from './clear-stale-models';+export {isWhisperModelCached} from './is-whisper-model-cached';+export type {IsWhisperModelCachedOptions} from './is-whisper-model-cached';export {disposeWhisperModel, loadWhisperModel} from './load-whisper-model';export type {DisposeWhisperModelOptions,@@ -12,18 +14,18 @@ export type {OnWhisperWebGpuModelLoadProgress,WhisperWebGpuModelLoadProgress,} from './load-whisper-model';-export {isWhisperModelCached} from './is-whisper-model-cached';-export type {IsWhisperModelCachedOptions} from './is-whisper-model-cached';-export {getAvailableModels, WHISPER_WEBGPU_MODELS} from './models';+export {WHISPER_WEBGPU_MODELS, getAvailableModels} from './models';export type {WhisperWebGpuModel, WhisperWebGpuModelInfo} from './models';-export {resampleTo16Khz, WHISPER_WEBGPU_SAMPLE_RATE} from './resample-to-16khz';+export {removeWhisperModel} from './remove-whisper-model';+export type {RemoveWhisperModelOptions} from './remove-whisper-model';+export {WHISPER_WEBGPU_SAMPLE_RATE, resampleTo16Khz} from './resample-to-16khz';export type {ResampleTo16KhzOptions} from './resample-to-16khz';export {toCaptions} from './to-captions';export type {ToCaptionsOptions, ToCaptionsResult} from './to-captions';export {transcribe} from './transcribe';export type {TranscribeOptions,- WhisperWebGpuTranscription,WhisperWebGpuTask,+ WhisperWebGpuTranscription,WhisperWebGpuWord,} from './transcribe';diff --git a/packages/whisper-webgpu/src/load-whisper-model.ts b/packages/whisper-webgpu/src/load-whisper-model.tsindex 17f5d79884..ce18e1d560 100644--- a/packages/whisper-webgpu/src/load-whisper-model.ts+++ b/packages/whisper-webgpu/src/load-whisper-model.ts@@ -27,6 +27,8 @@ type LoadedWhisperPipelineState = {loading: Promise<LoadedWhisperPipeline>;activeTranscriptions: number;onIdle: Array<() => void>;+ progressListeners: Set<OnWhisperWebGpuModelLoadProgress>;+ latestProgress: WhisperWebGpuModelLoadProgress | null;};const pipelines = new Map<WhisperWebGpuModel, LoadedWhisperPipelineState>();@@ -46,18 +48,52 @@ const getOrCreateWhisperPipeline = ({}: LoadWhisperModelOptions): {state: LoadedWhisperPipelineState;alreadyLoaded: boolean;- totalBytes: number;+ unsubscribe: () => void;} => {const modelInfo = getModelInfo(model);const totalBytes = modelInfo.webGpuDownloadSize;const existing = pipelines.get(model);if (existing) {- return {state: existing, alreadyLoaded: true, totalBytes};+ if (onProgress) {+ existing.progressListeners.add(onProgress);+ if (existing.latestProgress) {+ onProgress(existing.latestProgress);+ }+ }++ return {+ state: existing,+ alreadyLoaded: true,+ unsubscribe: () => {+ if (onProgress) {+ existing.progressListeners.delete(onProgress);+ }+ },+ };}+ const progressListeners = new Set<OnWhisperWebGpuModelLoadProgress>();+ if (onProgress) {+ progressListeners.add(onProgress);+ }++ const state: LoadedWhisperPipelineState = {+ loading: Promise.resolve(null as never),+ activeTranscriptions: 0,+ onIdle: [],+ progressListeners,+ latestProgress: null,+ };+ const emitProgress = (progress: WhisperWebGpuModelLoadProgress) => {+ state.latestProgress = progress;+ for (const listener of state.progressListeners) {+ listener(progress);+ }+ };+const loading = Promise.resolve().then(() => {return withRemotionModelHost(({pipeline}) => {- onProgress?.({+ emitProgress({status: 'loading',file: null,progress: 0,@@ -72,56 +108,50 @@ const getOrCreateWhisperPipeline = ({return pipeline('automatic-speech-recognition', hostedModelId, {device: 'webgpu',dtype: WHISPER_WEBGPU_DTYPE,- progress_callback: onProgress- ? (event) => {- const record = event as Record<string, unknown>;- if (- record.status === 'progress' &&- typeof record.file === 'string' &&- typeof record.loaded === 'number' &&- Number.isFinite(record.loaded)- ) {- loadedByFile.set(- record.file,- Math.max(loadedByFile.get(record.file) ?? 0, record.loaded),- );- const loadedBytes = [...loadedByFile.values()].reduce(- (sum, loaded) => sum + loaded,- 0,- );- lastProgress = Math.max(- lastProgress,- Math.min(loadedBytes / totalBytes, 0.99),- );- lastLoadedBytes = Math.max(lastLoadedBytes, loadedBytes);- onProgress({- status: 'loading',- file: null,- progress: lastProgress,- loadedBytes: lastLoadedBytes,- totalBytes,- });- }-- if (record.status === 'ready') {- onProgress({- status: 'ready',- file: null,- progress: 1,- loadedBytes: Math.max(lastLoadedBytes, totalBytes),- totalBytes,- });- }- }- : undefined,+ progress_callback: (event) => {+ const record = event as Record<string, unknown>;+ if (+ record.status === 'progress' &&+ typeof record.file === 'string' &&+ typeof record.loaded === 'number' &&+ Number.isFinite(record.loaded)+ ) {+ loadedByFile.set(+ record.file,+ Math.max(loadedByFile.get(record.file) ?? 0, record.loaded),+ );+ const loadedBytes = [...loadedByFile.values()].reduce(+ (sum, loaded) => sum + loaded,+ 0,+ );+ lastProgress = Math.max(+ lastProgress,+ Math.min(loadedBytes / totalBytes, 0.99),+ );+ lastLoadedBytes = Math.max(lastLoadedBytes, loadedBytes);+ emitProgress({+ status: 'loading',+ file: null,+ progress: lastProgress,+ loadedBytes: lastLoadedBytes,+ totalBytes,+ });+ }++ if (record.status === 'ready') {+ emitProgress({+ status: 'ready',+ file: null,+ progress: 1,+ loadedBytes: Math.max(lastLoadedBytes, totalBytes),+ totalBytes,+ });+ }+ },}) as Promise<LoadedWhisperPipeline>;});});- const state: LoadedWhisperPipelineState = {- loading,- activeTranscriptions: 0,- onIdle: [],- };+ state.loading = loading;pipelines.set(model, state);loading.catch(() => {if (pipelines.get(model) === state) {@@ -129,26 +159,29 @@ const getOrCreateWhisperPipeline = ({}});- return {state, alreadyLoaded: false, totalBytes};+ return {+ state,+ alreadyLoaded: false,+ unsubscribe: () => {+ if (onProgress) {+ state.progressListeners.delete(onProgress);+ }+ },+ };};export const loadWhisperModel = async ({model,onProgress,}: LoadWhisperModelOptions): Promise<LoadWhisperModelResult> => {- const {state, alreadyLoaded, totalBytes} = getOrCreateWhisperPipeline({+ const {state, alreadyLoaded, unsubscribe} = getOrCreateWhisperPipeline({model,onProgress,});- await state.loading;- if (alreadyLoaded) {- onProgress?.({- status: 'ready',- file: null,- progress: 1,- loadedBytes: totalBytes,- totalBytes,- });+ try {+ await state.loading;+ } finally {+ unsubscribe();}return {alreadyLoaded};@@ -163,25 +196,17 @@ export const withLoadedWhisperPipeline = async <ReturnValue>({onProgress?: OnWhisperWebGpuModelLoadProgress;run: (pipeline: LoadedWhisperPipeline) => Promise<ReturnValue>;}): Promise<ReturnValue> => {- const {state, alreadyLoaded, totalBytes} = getOrCreateWhisperPipeline({+ const {state, unsubscribe} = getOrCreateWhisperPipeline({model,onProgress,});state.activeTranscriptions++;try {const loaded = await state.loading;- if (alreadyLoaded) {- onProgress?.({- status: 'ready',- file: null,- progress: 1,- loadedBytes: totalBytes,- totalBytes,- });- }-+ unsubscribe();return await run(loaded);} finally {+ unsubscribe();state.activeTranscriptions--;if (state.activeTranscriptions === 0) {for (const resolve of state.onIdle.splice(0)) {diff --git a/packages/whisper-webgpu/src/remove-whisper-model.ts b/packages/whisper-webgpu/src/remove-whisper-model.tsnew file mode 100644index 0000000000..e5e05dc0ce--- /dev/null+++ b/packages/whisper-webgpu/src/remove-whisper-model.ts@@ -0,0 +1,27 @@+import {disposeWhisperModel} from './load-whisper-model';+import {+ getHostedModelId,+ WHISPER_WEBGPU_DTYPE,+ type WhisperWebGpuModel,+} from './models';+import {withRemotionModelHost} from './with-remotion-model-host';++export type RemoveWhisperModelOptions = {+ model: WhisperWebGpuModel;+};++export const removeWhisperModel = async ({+ model,+}: RemoveWhisperModelOptions): Promise<void> => {+ await disposeWhisperModel({model});+ await withRemotionModelHost(({ModelRegistry}) => {+ return ModelRegistry.clear_pipeline_cache(+ 'automatic-speech-recognition',+ getHostedModelId(model),+ {+ device: 'webgpu',+ dtype: WHISPER_WEBGPU_DTYPE,+ },+ );+ });+};diff --git a/packages/whisper-webgpu/src/test/transcribe.test.ts b/packages/whisper-webgpu/src/test/transcribe.test.tsindex 71d4719023..5aed3ca4b8 100644--- a/packages/whisper-webgpu/src/test/transcribe.test.ts+++ b/packages/whisper-webgpu/src/test/transcribe.test.ts@@ -46,6 +46,13 @@ let cacheCheckEnvironment:}| undefined;let cacheCheckError: Error | null = null;+let cacheClear:+ | {+ task: string;+ modelId: string;+ options: Record<string, unknown>;+ }+ | undefined;const originalTransformersEnvironment = {remoteHost: 'https://huggingface.co/',@@ -80,6 +87,14 @@ const fakePipeline = Object.assign(mock.module('@huggingface/transformers', () => ({env: transformersEnvironment,ModelRegistry: {+ clear_pipeline_cache: (+ task: string,+ modelId: string,+ options: Record<string, unknown>,+ ) => {+ cacheClear = {task, modelId, options};+ return Promise.resolve({filesDeleted: 5, filesCached: 5, files: []});+ },is_pipeline_cached: (task: string,modelId: string,@@ -584,8 +599,12 @@ test('validates and forwards transcription settings through transcribe()', async});test('shares concurrent initialization and keeps the model host scoped until every operation completes', async () => {- const {disposeWhisperModel, isWhisperModelCached, loadWhisperModel} =- await import('../index');+ const {+ disposeWhisperModel,+ isWhisperModelCached,+ loadWhisperModel,+ transcribe,+ } = await import('../index');let releaseInitialization: () => void = () => {};pipelineInitializationGate = new Promise<void>((resolve) => {releaseInitialization = resolve;@@ -595,10 +614,28 @@ test('shares concurrent initialization and keeps the model host scoped until eve});const initializationsBeforeLoading = pipelineInitializationCount;const disposalsBeforeLoading = disposeCalls;-- const firstLoad = loadWhisperModel({model: 'base'});- const secondLoad = loadWhisperModel({model: 'base'});+ const firstProgress: number[] = [];+ const secondProgress: number[] = [];++ const firstLoad = loadWhisperModel({+ model: 'base',+ onProgress: ({progress}) => {+ if (progress !== null) {+ firstProgress.push(progress);+ }+ },+ });await initializationStarted;+ const transcription = transcribe({+ channelWaveform: new Float32Array(16_000),+ language: 'en',+ model: 'base',+ onModelLoadProgress: ({progress}) => {+ if (progress !== null) {+ secondProgress.push(progress);+ }+ },+ });expect(pipelineInitializationCount - initializationsBeforeLoading).toBe(1);expect(transformersEnvironment).toEqual({remoteHost: 'https://remotion.media/',@@ -626,10 +663,10 @@ test('shares concurrent initialization and keeps the model host scoped until eveexpect(disposeCalls).toBe(disposalsBeforeLoading);releaseInitialization();- await expect(Promise.all([firstLoad, secondLoad])).resolves.toEqual([- {alreadyLoaded: false},- {alreadyLoaded: true},- ]);+ await expect(firstLoad).resolves.toEqual({alreadyLoaded: false});+ await expect(transcription).resolves.toMatchObject({model: 'base'});+ expect(firstProgress.at(-1)).toBe(1);+ expect(secondProgress).toEqual(firstProgress);await disposal;expect(disposeCalls).toBe(disposalsBeforeLoading + 1);expect(transformersEnvironment).toEqual(originalTransformersEnvironment);@@ -637,6 +674,26 @@ test('shares concurrent initialization and keeps the model host scoped until eveonPipelineInitializationStarted = null;});+test('removes a downloaded model from memory and the persistent cache', async () => {+ const {loadWhisperModel, removeWhisperModel} = await import('../index');+ const disposalsBeforeRemoval = disposeCalls;+ await loadWhisperModel({model: 'tiny.en'});+ await removeWhisperModel({model: 'tiny.en'});++ expect(disposeCalls).toBe(disposalsBeforeRemoval + 1);+ expect(cacheClear).toEqual({+ task: 'automatic-speech-recognition',+ modelId: 'whisper-tiny.en_timestamped-v1',+ options: {+ device: 'webgpu',+ dtype: {+ decoder_model_merged: 'q4',+ encoder_model: 'fp32',+ },+ },+ });+});+test('only restores Transformers environment fields left unchanged by the consumer', async () => {const {disposeWhisperModel, loadWhisperModel} = await import('../index');let releaseInitialization: () => void = () => {};