🎥 Make videos programmatically with React
refactor
Jonny Burgerb2adf7d6640a
diff --git a/packages/whisper-wasm/src/constants.ts b/packages/whisper-wasm/src/constants.tsnew file mode 100644index 0000000000..404d11a531--- /dev/null+++ b/packages/whisper-wasm/src/constants.ts@@ -0,0 +1,4 @@+export const DB_NAME = 'whisper-wasm';+export const FILE_DESTINATION = 'whisper.bin';+export const DB_VERSION = 1;+export const DB_OBJECT_STORE_NAME = 'models';diff --git a/packages/whisper-wasm/src/db/get-object-from-db.ts b/packages/whisper-wasm/src/db/get-object-from-db.tsnew file mode 100644index 0000000000..36b776b7bb--- /dev/null+++ b/packages/whisper-wasm/src/db/get-object-from-db.ts@@ -0,0 +1,12 @@+export const getObjectFromDb = (objectStore: IDBObjectStore, key: string) => {+ return new Promise<Uint8Array>((resolve, reject) => {+ const request = objectStore.get(key);+ request.onsuccess = () => {+ resolve(request.result as Uint8Array);+ };++ request.onerror = () => {+ reject(request.error);+ };+ });+};diff --git a/packages/whisper-wasm/src/db/open-db.ts b/packages/whisper-wasm/src/db/open-db.tsnew file mode 100644index 0000000000..9c3f9d4f2d--- /dev/null+++ b/packages/whisper-wasm/src/db/open-db.ts@@ -0,0 +1,59 @@+import {DB_NAME, DB_OBJECT_STORE_NAME, DB_VERSION} from '../constants';++export const openDb = () => {+ return new Promise<IDBObjectStore>((resolve, reject) => {+ const rq = indexedDB.open(DB_NAME, DB_VERSION);++ rq.onupgradeneeded = (event) => {+ try {+ const db = rq.result;+ if (event.oldVersion < DB_VERSION) {+ db.createObjectStore(DB_OBJECT_STORE_NAME, {autoIncrement: false});+ } else {+ const {transaction} = event.currentTarget as IDBOpenDBRequest;+ if (!transaction) {+ throw new Error('No transaction available during upgrade');+ }++ const objectStore = transaction.objectStore(DB_OBJECT_STORE_NAME);+ if (!objectStore) {+ throw new Error('Could not access object store during upgrade');+ }++ objectStore.clear();+ }+ } catch (err) {+ reject(new Error(`Failed to upgrade database: ${err}`));+ }+ };++ rq.onsuccess = () => {+ try {+ const db = rq.result;+ const transaction = db.transaction([DB_OBJECT_STORE_NAME], 'readonly');++ transaction.onerror = () => {+ reject(new Error('Transaction failed'));+ };++ transaction.onabort = () => {+ reject(new Error('Transaction aborted'));+ };++ const objectStore = transaction.objectStore(DB_OBJECT_STORE_NAME);+ resolve(objectStore);+ } catch (err) {+ reject(new Error(`Failed to open database: ${err}`));+ }+ };++ rq.onerror = () => {+ const error = rq.error?.message ?? 'Unknown error';+ reject(new Error(`Failed to open IndexedDB: ${error}`));+ };++ rq.onblocked = () => {+ reject(new Error('Database is blocked by another connection'));+ };+ });+};diff --git a/packages/whisper-wasm/src/download-model.ts b/packages/whisper-wasm/src/download-model.tsnew file mode 100644index 0000000000..fc8fdd1bd2--- /dev/null+++ b/packages/whisper-wasm/src/download-model.ts@@ -0,0 +1,53 @@+export const fetchRemote = async ({+ url,+ onProgress,+}: {+ url: string;+ onProgress: (progress: number) => void;+}) => {+ // start the fetch+ const response = await fetch(url, {method: 'get'});+ if (!response.ok || !response.body) {+ throw new Error(`failed to fetch: ${url}`);+ }++ const contentLength = response.headers.get('content-length') as string;+ // hugging face servers do include this header+ const total = parseInt(contentLength, 10);+ const reader = response.body.getReader();++ const chunks: Uint8Array[] = [];+ let receivedLength = 0;+ let progressLast = -1;++ while (true) {+ const {done, value} = await reader.read();++ if (done) {+ break;+ }++ chunks.push(value);+ receivedLength += value.length;++ if (contentLength) {+ const progressPercentage = Math.round((receivedLength / total) * 100);+ onProgress(progressPercentage);++ const progressCur = Math.round((receivedLength / total) * 10);+ if (progressCur !== progressLast) {+ progressLast = progressCur;+ }+ }+ }++ let position = 0;+ const chunksAll = new Uint8Array(receivedLength);++ for (const chunk of chunks) {+ chunksAll.set(chunk, position);+ position += chunk.length;+ }++ return chunksAll;+};diff --git a/packages/whisper-wasm/src/download-whisper-model.ts b/packages/whisper-wasm/src/download-whisper-model.tsindex 1b49637a38..6fbc5ad1a0 100644--- a/packages/whisper-wasm/src/download-whisper-model.ts+++ b/packages/whisper-wasm/src/download-whisper-model.ts@@ -1,12 +1,17 @@/* eslint-disable no-console *//* eslint-disable new-cap */import {checkForHeaders} from './check-for-headers';+import {+ DB_NAME,+ DB_OBJECT_STORE_NAME,+ DB_VERSION,+ FILE_DESTINATION,+} from './constants';+import {getObjectFromDb} from './db/get-object-from-db';+import {openDb} from './db/open-db';+import {fetchRemote} from './download-model';import {Module} from './mod';-const dbName = 'whisper-wasm';-const dst = 'whisper.bin';-const dbVersion = 1;-const MODELS = ['tiny','tiny.en',@@ -35,60 +40,6 @@ const storeFS = (fname: string, buf: any) => {Module.FS_createDataFile('/', fname, buf, true, true, undefined);};-const fetchRemote = async ({- url,- progressCallback,-}: {- url: string;- progressCallback?: (arg0: number) => void;-}) => {- // start the fetch- const response = await fetch(url, {method: 'get'});- if (!response.ok || !response.body) {- throw new Error(`failed to fetch: ${url}`);- }-- const contentLength = response.headers.get('content-length') as string;- // hugging face servers do include this header- const total = parseInt(contentLength, 10);- const reader = response.body.getReader();-- const chunks: Uint8Array[] = [];- let receivedLength = 0;- let progressLast = -1;-- while (true) {- const {done, value} = await reader.read();-- if (done) {- break;- }-- chunks.push(value);- receivedLength += value.length;-- if (contentLength) {- const progressPercentage = Math.round((receivedLength / total) * 100);- progressCallback?.(progressPercentage);-- const progressCur = Math.round((receivedLength / total) * 10);- if (progressCur !== progressLast) {- progressLast = progressCur;- }- }- }-- let position = 0;- const chunksAll = new Uint8Array(receivedLength);-- for (const chunk of chunks) {- chunksAll.set(chunk, position);- position += chunk.length;- }-- return chunksAll;-};-const postModelLoaded = (data: Uint8Array, url: string) => {return new Promise((resolve, reject) => {if (!data) {@@ -96,101 +47,60 @@ const postModelLoaded = (data: Uint8Array, url: string) => {return;}- const rq = indexedDB.open(dbName, dbVersion);- rq.onsuccess = function (event) {- // @ts-expect-error- const db = event.target.result;- const objectStore = db- .transaction(['models'], 'readwrite')- .objectStore('models');- let putRq;+ const rq = indexedDB.open(DB_NAME, DB_VERSION);+ rq.onsuccess = function () {+ const objectStore = rq.result+ .transaction([DB_OBJECT_STORE_NAME], 'readwrite')+ .objectStore(DB_OBJECT_STORE_NAME);try {- putRq = objectStore.put(data, url);+ const putRq = objectStore.put(data, url);++ putRq.onsuccess = () => {+ storeFS(FILE_DESTINATION, data);+ resolve('stored successfully');+ };++ putRq.onerror = () => {+ reject(new Error(`Failed to store "${url}" in IndexedDB`));+ };} catch (e) {reject(new Error(`Failed to store "${url}" in IndexedDB: ${e}`));- return;}-- putRq.onsuccess = () => {- console.log(`"${url}" stored in IndexedDB`);- storeFS(dst, data);- resolve('stored successfully');- };-- putRq.onerror = () => {- reject(new Error(`Failed to store "${url}" in IndexedDB`));- };};rq.onerror = () => reject(new Error('Failed to open IndexedDB'));});};-const loadModel = ({+const loadModel = async ({url,onProgress,}: {url: string;onProgress: (progress: number) => void;}) => {- return new Promise((resolve, reject) => {- checkForHeaders();- if (!navigator.storage || !navigator.storage.estimate) {- console.log('Could not estimate the storage');- } else {- navigator.storage.estimate().then((estimate) => {- console.log('Estimate quota:', estimate.quota);- console.log('Estimate usage:', estimate.usage);- });- }+ checkForHeaders();- const rq = indexedDB.open(dbName, dbVersion);-- rq.onupgradeneeded = (event) => {- const db = (event.target as IDBOpenDBRequest).result;- if (event.oldVersion < 1) {- db.createObjectStore('models', {autoIncrement: false});- console.log('DB created');- } else {- const os = (- event.currentTarget as IDBOpenDBRequest- ).transaction?.objectStore('models');- os?.clear();- console.log('DB cleared');- }- };+ if (!navigator.storage || !navigator.storage.estimate) {+ throw new Error(+ 'navigator.storage.estimate() API is not available in this environment',+ );+ }- rq.onsuccess = (event) => {- const db = (event.target as IDBOpenDBRequest).result;- const transaction = db.transaction(['models'], 'readonly');- const objectStore = transaction.objectStore('models');- const innerRq = objectStore.get(url);-- innerRq.onsuccess = () => {- if (innerRq.result) {- console.log('Model already in IndexedDB');- storeFS(dst, innerRq.result);- resolve('Model loaded successfully');- } else {- // Now postModelLoaded() returns a Promise- fetchRemote({url, progressCallback: onProgress})- .then((data) => postModelLoaded(data, url))- .then(() => resolve('Loaded model after downloading successfully'))- .catch((error) =>- reject(new Error(`Failed to fetch or store model: ${error}`)),- );- }- };-- innerRq.onerror = () =>- reject(new Error('Failed to get data from IndexedDB'));- transaction.onabort = () =>- reject(new Error('Failed to open IndexedDB: abort'));- };+ const estimate = await navigator.storage.estimate();+ console.log('Estimate quota:', estimate.quota);+ console.log('Estimate usage:', estimate.usage);- rq.onerror = () => reject(new Error('Failed to open IndexedDB'));- rq.onblocked = () => reject(new Error('Failed to open IndexedDB: cancel'));- });+ const objectStore = await openDb();++ const result = await getObjectFromDb(objectStore, url);+ if (result) {+ console.log('Model already in IndexedDB', result);+ storeFS(FILE_DESTINATION, result);+ } else {+ const data = await fetchRemote({url, onProgress});+ await postModelLoaded(data, url);+ }};export const downloadWhisperModel = async ({