Skip to content

🎥 Make videos programmatically with React

Fix for Issue #4961 (@remotion/install-whisper-cpp Fails with Deprecation Warning in whisper.cpp 1.7.4)

Udit Kumarca724bbce22f
diff --git a/packages/install-whisper-cpp/src/install-whisper-cpp.ts b/packages/install-whisper-cpp/src/install-whisper-cpp.ts
index a4f46698a9..94db56f098 100644
--- a/packages/install-whisper-cpp/src/install-whisper-cpp.ts
+++ b/packages/install-whisper-cpp/src/install-whisper-cpp.ts
@@ -4,187 +4,205 @@ import fs, {existsSync, rmSync} from 'fs';
import os from 'os';
import path from 'path';
import {downloadFile} from './download';
+import {compareVersions} from './utils';
const getIsSemVer = (str: string) => {
- return /^[\d]{1}\.[\d]{1,2}\.+/.test(str);
+ return /^[\d]{1}\.[\d]{1,2}\.+/.test(str);
};
const execute = ({
- printOutput,
- signal,
- cwd,
- shell,
- args,
- bin,
+ printOutput,
+ signal,
+ cwd,
+ shell,
+ args,
+ bin,
}: {
- printOutput: boolean;
- signal: AbortSignal | null;
- cwd: string | null;
- shell: string | null;
- bin: string;
- args: string[];
+ printOutput: boolean;
+ signal: AbortSignal | null;
+ cwd: string | null;
+ shell: string | null;
+ bin: string;
+ args: string[];
}) => {
- const stdio: StdioOptions = printOutput ? 'inherit' : 'ignore';
-
- return new Promise<void>((resolve, reject) => {
- const child = spawn(bin, args, {
- stdio,
- signal: signal ?? undefined,
- cwd: cwd ?? undefined,
- shell: shell ?? undefined,
- });
-
- child.on('exit', (code, exitSignal) => {
- if (code !== 0) {
- reject(
- new Error(
- `Error while executing ${bin} ${args.join(' ')}. Exit code: ${code}, signal: ${exitSignal}`,
- ),
- );
- return;
- }
-
- resolve();
- });
- });
+ const stdio: StdioOptions = printOutput ? 'inherit' : 'ignore';
+
+ return new Promise<void>((resolve, reject) => {
+ const child = spawn(bin, args, {
+ stdio,
+ signal: signal ?? undefined,
+ cwd: cwd ?? undefined,
+ shell: shell ?? undefined,
+ });
+
+ child.on('exit', (code, exitSignal) => {
+ if (code !== 0) {
+ reject(
+ new Error(
+ `Error while executing ${bin} ${args.join(' ')}. Exit code: ${code}, signal: ${exitSignal}`,
+ ),
+ );
+ return;
+ }
+
+ resolve();
+ });
+ });
};
const installForWindows = async ({
- version,
- to,
- printOutput,
- signal,
+ version,
+ to,
+ printOutput,
+ signal,
}: {
- version: string;
- to: string;
- printOutput: boolean;
- signal: AbortSignal | null;
+ version: string;
+ to: string;
+ printOutput: boolean;
+ signal: AbortSignal | null;
}) => {
- if (!getIsSemVer(version)) {
- throw new Error(`Non-semantic version provided. Only releases of Whisper.cpp are supported on Windows (e.g., 1.5.4). Provided version:
+ if (!getIsSemVer(version)) {
+ throw new Error(`Non-semantic version provided. Only releases of Whisper.cpp are supported on Windows (e.g., 1.5.4). Provided version:
${version}. See https://www.remotion.dev/docs/install-whisper-cpp/install-whisper-cpp#version for more information.`);
- }
-
- const url =
- version === '1.5.5'
- ? 'https://remotion-ffmpeg-binaries.s3.eu-central-1.amazonaws.com/whisper-bin-x64-1-5-5.zip'
- : `https://github.com/ggerganov/whisper.cpp/releases/download/v${version}/whisper-bin-x64.zip`;
-
- const filePath = path.join(process.cwd(), 'whisper-bin-x64.zip');
- const fileStream = fs.createWriteStream(filePath);
-
- await downloadFile({
- fileStream,
- printOutput,
- url,
- onProgress: undefined,
- signal,
- });
-
- await execute({
- shell: 'powershell',
- printOutput,
- signal,
- cwd: null,
- bin: 'Expand-Archive',
- args: ['-Force', filePath, to],
- });
-
- rmSync(filePath);
+ }
+
+ const url =
+ version === '1.5.5'
+ ? 'https://remotion-ffmpeg-binaries.s3.eu-central-1.amazonaws.com/whisper-bin-x64-1-5-5.zip'
+ : `https://github.com/ggerganov/whisper.cpp/releases/download/v${version}/whisper-bin-x64.zip`;
+
+ const filePath = path.join(process.cwd(), 'whisper-bin-x64.zip');
+ const fileStream = fs.createWriteStream(filePath);
+
+ await downloadFile({
+ fileStream,
+ printOutput,
+ url,
+ onProgress: undefined,
+ signal,
+ });
+
+ await execute({
+ shell: 'powershell',
+ printOutput,
+ signal,
+ cwd: null,
+ bin: 'Expand-Archive',
+ args: ['-Force', filePath, to],
+ });
+
+ rmSync(filePath);
};
const installWhisperForUnix = async ({
- version,
- to,
- printOutput,
- signal,
+ version,
+ to,
+ printOutput,
+ signal,
}: {
- version: string;
- to: string;
- printOutput: boolean;
- signal: AbortSignal | null;
+ version: string;
+ to: string;
+ printOutput: boolean;
+ signal: AbortSignal | null;
}): Promise<void> => {
- await execute({
- bin: 'git',
- args: ['clone', 'https://github.com/ggerganov/whisper.cpp.git', to],
- printOutput,
- signal,
- cwd: null,
- shell: null,
- });
-
- const ref = getIsSemVer(version) ? `v${version}` : version;
-
- await execute({
- bin: 'git',
- args: ['checkout', ref],
- printOutput,
- cwd: to,
- signal,
- shell: null,
- });
-
- await execute({
- args: [],
- bin: 'make',
- cwd: to,
- signal,
- printOutput,
- shell: null,
- });
+ await execute({
+ bin: 'git',
+ args: ['clone', 'https://github.com/ggerganov/whisper.cpp.git', to],
+ printOutput,
+ signal,
+ cwd: null,
+ shell: null,
+ });
+
+ const ref = getIsSemVer(version) ? `v${version}` : version;
+
+ await execute({
+ bin: 'git',
+ args: ['checkout', ref],
+ printOutput,
+ cwd: to,
+ signal,
+ shell: null,
+ });
+
+ await execute({
+ args: [],
+ bin: 'make',
+ cwd: to,
+ signal,
+ printOutput,
+ shell: null,
+ });
};
-export const getWhisperExecutablePath = (whisperPath: string) => {
- return os.platform() === 'win32'
- ? path.join(path.resolve(process.cwd(), whisperPath), 'main.exe')
- : path.join(path.resolve(process.cwd(), whisperPath), './main');
+export const getWhisperExecutablePath = (
+ whisperPath: string,
+ whisperCppVersion: string,
+) => {
+ // INFO: 'main.exe' is deprecated.
+ let cppBin = 'main';
+ if (compareVersions(whisperCppVersion, '1.7.4') >= 0) {
+ cppBin = 'whisper-cli';
+ }
+
+ return os.platform() === 'win32'
+ ? path.join(path.resolve(process.cwd(), whisperPath), `${cppBin}.exe`)
+ : path.join(path.resolve(process.cwd(), whisperPath), `./${cppBin}`);
};
export const installWhisperCpp = async ({
- version,
- to,
- printOutput = true,
- signal,
+ version,
+ to,
+ printOutput = true,
+ signal,
}: {
- version: string;
- to: string;
- signal?: AbortSignal | null;
- printOutput?: boolean;
+ version: string;
+ to: string;
+ signal?: AbortSignal | null;
+ printOutput?: boolean;
}): Promise<{
- alreadyExisted: boolean;
+ alreadyExisted: boolean;
}> => {
- if (existsSync(to)) {
- if (!existsSync(getWhisperExecutablePath(to))) {
- if (printOutput) {
- throw new Error(
- `Whisper folder ${to} exists but the executable (${getWhisperExecutablePath(to)}) is missing. Delete ${to} and try again.`,
- );
- }
-
- return Promise.resolve({alreadyExisted: false});
- }
-
- if (printOutput) {
- console.log(`Whisper already exists at ${to}`);
- }
-
- return Promise.resolve({alreadyExisted: true});
- }
-
- if (process.platform === 'darwin' || process.platform === 'linux') {
- await installWhisperForUnix({
- version,
- to,
- printOutput,
- signal: signal ?? null,
- });
- return Promise.resolve({alreadyExisted: false});
- }
-
- if (process.platform === 'win32') {
- await installForWindows({version, to, printOutput, signal: signal ?? null});
- return Promise.resolve({alreadyExisted: false});
- }
-
- throw new Error(`Unsupported platform: ${process.platform}`);
+ if (existsSync(to)) {
+ if (!existsSync(getWhisperExecutablePath(to, version))) {
+ if (printOutput) {
+ throw new Error(
+ `Whisper folder ${to} exists but the executable (${getWhisperExecutablePath(
+ to,
+ version,
+ )}) is missing. Delete ${to} and try again.`,
+ );
+ }
+
+ return Promise.resolve({alreadyExisted: false});
+ }
+
+ if (printOutput) {
+ console.log(`Whisper already exists at ${to}`);
+ }
+
+ return Promise.resolve({alreadyExisted: true});
+ }
+
+ if (process.platform === 'darwin' || process.platform === 'linux') {
+ await installWhisperForUnix({
+ version,
+ to,
+ printOutput,
+ signal: signal ?? null,
+ });
+ return Promise.resolve({alreadyExisted: false});
+ }
+
+ if (process.platform === 'win32') {
+ await installForWindows({
+ version,
+ to,
+ printOutput,
+ signal: signal ?? null,
+ });
+ return Promise.resolve({alreadyExisted: false});
+ }
+
+ throw new Error(`Unsupported platform: ${process.platform}`);
};
diff --git a/packages/install-whisper-cpp/src/transcribe.ts b/packages/install-whisper-cpp/src/transcribe.ts
index ad7c5a7fb8..9fe0628c72 100644
--- a/packages/install-whisper-cpp/src/transcribe.ts
+++ b/packages/install-whisper-cpp/src/transcribe.ts
@@ -66,27 +66,27 @@ type Result = {
};
export type TranscriptionJson<WithTokenLevelTimestamp extends boolean> = {
- systeminfo: string;
- model: Model;
- params: Params;
- result: Result;
- transcription: true extends WithTokenLevelTimestamp
- ? TranscriptionItemWithTimestamp[]
- : TranscriptionItem[];
+ systeminfo: string;
+ model: Model;
+ params: Params;
+ result: Result;
+ transcription: true extends WithTokenLevelTimestamp
+ ? TranscriptionItemWithTimestamp[]
+ : TranscriptionItem[];
};
const isWavFile = (inputPath: string) => {
- const splitted = inputPath.split('.');
- if (!splitted) {
- return false;
- }
+ const splitted = inputPath.split('.');
+ if (!splitted) {
+ return false;
+ }
- return splitted[splitted.length - 1] === 'wav';
+ return splitted[splitted.length - 1] === 'wav';
};
const readJson = async (jsonPath: string) => {
- const data = await fs.promises.readFile(jsonPath, 'utf8');
- return JSON.parse(data);
+ const data = await fs.promises.readFile(jsonPath, 'utf8');
+ return JSON.parse(data);
};
export type TranscribeOnProgress = (progress: number) => void;
@@ -94,233 +94,238 @@ export type TranscribeOnProgress = (progress: number) => void;
// https://github.com/ggerganov/whisper.cpp/blob/fe36c909715e6751277ddb020e7892c7670b61d4/examples/main/main.cpp#L989-L999
// https://github.com/remotion-dev/remotion/issues/4168
export const modelToDtw = (model: WhisperModel): string => {
- if (model === 'large-v3-turbo') {
- return 'large.v3.turbo';
- }
+ if (model === 'large-v3-turbo') {
+ return 'large.v3.turbo';
+ }
- if (model === 'large-v3') {
- return 'large.v3';
- }
+ if (model === 'large-v3') {
+ return 'large.v3';
+ }
- if (model === 'large-v2') {
- return 'large.v2';
- }
+ if (model === 'large-v2') {
+ return 'large.v2';
+ }
- if (model === 'large-v1') {
- return 'large.v1';
- }
+ if (model === 'large-v1') {
+ return 'large.v1';
+ }
- return model;
+ return model;
};
const transcribeToTemporaryFile = async ({
- fileToTranscribe,
- whisperPath,
- model,
- tmpJSONPath,
- modelFolder,
- translate,
- tokenLevelTimestamps,
- printOutput,
- tokensPerItem,
- language,
- splitOnWord,
- signal,
- onProgress,
+ fileToTranscribe,
+ whisperPath,
+ whisperCppVersion,
+ model,
+ tmpJSONPath,
+ modelFolder,
+ translate,
+ tokenLevelTimestamps,
+ printOutput,
+ tokensPerItem,
+ language,
+ splitOnWord,
+ signal,
+ onProgress,
}: {
- fileToTranscribe: string;
- whisperPath: string;
- model: WhisperModel;
- tmpJSONPath: string;
- modelFolder: string | null;
- translate: boolean;
- tokenLevelTimestamps: boolean;
- printOutput: boolean;
- tokensPerItem: number | null;
- language: Language | null;
- splitOnWord: boolean | null;
- signal: AbortSignal | null;
- onProgress: TranscribeOnProgress | null;
+ fileToTranscribe: string;
+ whisperPath: string;
+ whisperCppVersion: string;
+ model: WhisperModel;
+ tmpJSONPath: string;
+ modelFolder: string | null;
+ translate: boolean;
+ tokenLevelTimestamps: boolean;
+ printOutput: boolean;
+ tokensPerItem: number | null;
+ language: Language | null;
+ splitOnWord: boolean | null;
+ signal: AbortSignal | null;
+ onProgress: TranscribeOnProgress | null;
}): Promise<{
outputPath: string;
}> => {
- const modelPath = getModelPath(modelFolder ?? whisperPath, model);
-
- if (!fs.existsSync(modelPath)) {
- throw new Error(
- `Error: Model ${model} does not exist at ${
- modelFolder ? modelFolder : modelPath
- }. Check out the downloadWhisperModel() API at https://www.remotion.dev/docs/install-whisper-cpp/download-whisper-model to see how to install whisper models`,
- );
- }
-
- const executable = getWhisperExecutablePath(whisperPath);
-
- const args = [
- '-f',
- fileToTranscribe,
- '--output-file',
- tmpJSONPath,
- '--output-json',
- tokensPerItem ? ['--max-len', tokensPerItem] : null,
- '-ojf', // Output full JSON
- tokenLevelTimestamps ? ['--dtw', modelToDtw(model)] : null,
- model ? [`-m`, `${modelPath}`] : null,
- ['-pp'], // print progress
- translate ? '-tr' : null,
- language ? ['-l', language.toLowerCase()] : null,
- splitOnWord ? ['--split-on-word', splitOnWord] : null,
- ]
- .flat(1)
- .filter(Boolean) as string[];
-
- const outputPath = await new Promise<string>((resolve, reject) => {
- const task = spawn(executable, args, {
- cwd: path.resolve(process.cwd(), whisperPath),
- signal: signal ?? undefined,
- });
- const predictedPath = `${tmpJSONPath}.json`;
-
- let output: string = '';
-
- const onData = (data: Buffer) => {
- const str = data.toString('utf-8');
- const hasProgress = str.includes('progress =');
- if (hasProgress) {
- const progress = parseFloat(str.split('progress =')[1].trim());
- onProgress?.(progress / 100);
- }
-
- output += str;
-
- // Sometimes it hangs here
- if (str.includes('ggml_metal_free: deallocating')) {
- task.kill();
- }
- };
-
- let stderr = '';
-
- const onStderr = (data: Buffer) => {
- onData(data);
- const utf8 = data.toString('utf-8');
- stderr += utf8;
- if (printOutput) {
- process.stderr.write(utf8);
- }
- };
-
- const onStdout = (data: Buffer) => {
- onData(data);
- if (printOutput) {
- process.stdout.write(data.toString('utf-8'));
- }
- };
-
- task.stdout.on('data', onStdout);
- task.stderr.on('data', onStderr);
-
- task.on('exit', (code, exitSignal) => {
- // Whisper sometimes files also with error code 0
- // https://github.com/ggerganov/whisper.cpp/pull/1952/files
-
- if (existsSync(predictedPath)) {
- resolve(predictedPath);
- onProgress?.(1);
- return;
- }
-
- if (exitSignal) {
- reject(
- new Error(`Process was killed with signal ${exitSignal}: ${output}`),
- );
- return;
- }
-
- if (stderr.includes('must be 16 kHz')) {
- reject(
- new Error(
- 'wav file must be 16 kHz - use this command to make it so: "ffmpeg -i input.wav -ar 16000 output.wav -y"',
- ),
- );
- }
-
- reject(
- new Error(
- `No transcription was created (process exited with code ${code}): ${output}`,
- ),
- );
- });
- });
-
- return {outputPath};
+ const modelPath = getModelPath(modelFolder ?? whisperPath, model);
+
+ if (!fs.existsSync(modelPath)) {
+ throw new Error(
+ `Error: Model ${model} does not exist at ${
+ modelFolder ? modelFolder : modelPath
+ }. Check out the downloadWhisperModel() API at https://www.remotion.dev/docs/install-whisper-cpp/download-whisper-model to see how to install whisper models`,
+ );
+ }
+
+ const executable = getWhisperExecutablePath(whisperPath, whisperCppVersion);
+
+ const args = [
+ '-f',
+ fileToTranscribe,
+ '--output-file',
+ tmpJSONPath,
+ '--output-json',
+ tokensPerItem ? ['--max-len', tokensPerItem] : null,
+ '-ojf', // Output full JSON
+ tokenLevelTimestamps ? ['--dtw', modelToDtw(model)] : null,
+ model ? [`-m`, `${modelPath}`] : null,
+ ['-pp'], // print progress
+ translate ? '-tr' : null,
+ language ? ['-l', language.toLowerCase()] : null,
+ splitOnWord ? ['--split-on-word', splitOnWord] : null,
+ ]
+ .flat(1)
+ .filter(Boolean) as string[];
+
+ const outputPath = await new Promise<string>((resolve, reject) => {
+ const task = spawn(executable, args, {
+ cwd: path.resolve(process.cwd(), whisperPath),
+ signal: signal ?? undefined,
+ });
+ const predictedPath = `${tmpJSONPath}.json`;
+
+ let output: string = '';
+
+ const onData = (data: Buffer) => {
+ const str = data.toString('utf-8');
+ const hasProgress = str.includes('progress =');
+ if (hasProgress) {
+ const progress = parseFloat(str.split('progress =')[1].trim());
+ onProgress?.(progress / 100);
+ }
+
+ output += str;
+
+ // Sometimes it hangs here
+ if (str.includes('ggml_metal_free: deallocating')) {
+ task.kill();
+ }
+ };
+
+ let stderr = '';
+
+ const onStderr = (data: Buffer) => {
+ onData(data);
+ const utf8 = data.toString('utf-8');
+ stderr += utf8;
+ if (printOutput) {
+ process.stderr.write(utf8);
+ }
+ };
+
+ const onStdout = (data: Buffer) => {
+ onData(data);
+ if (printOutput) {
+ process.stdout.write(data.toString('utf-8'));
+ }
+ };
+
+ task.stdout.on('data', onStdout);
+ task.stderr.on('data', onStderr);
+
+ task.on('exit', (code, exitSignal) => {
+ // Whisper sometimes files also with error code 0
+ // https://github.com/ggerganov/whisper.cpp/pull/1952/files
+
+ if (existsSync(predictedPath)) {
+ resolve(predictedPath);
+ onProgress?.(1);
+ return;
+ }
+
+ if (exitSignal) {
+ reject(
+ new Error(`Process was killed with signal ${exitSignal}: ${output}`),
+ );
+ return;
+ }
+
+ if (stderr.includes('must be 16 kHz')) {
+ reject(
+ new Error(
+ 'wav file must be 16 kHz - use this command to make it so: "ffmpeg -i input.wav -ar 16000 output.wav -y"',
+ ),
+ );
+ }
+
+ reject(
+ new Error(
+ `No transcription was created (process exited with code ${code}): ${output}`,
+ ),
+ );
+ });
+ });
+
+ return {outputPath};
};
export const transcribe = async <HasTokenLevelTimestamps extends boolean>({
- inputPath,
- whisperPath,
- model,
- modelFolder,
- translateToEnglish = false,
- tokenLevelTimestamps,
- printOutput = true,
- tokensPerItem,
- language,
- splitOnWord,
- signal,
- onProgress,
+ inputPath,
+ whisperPath,
+ whisperCppVersion,
+ model,
+ modelFolder,
+ translateToEnglish = false,
+ tokenLevelTimestamps,
+ printOutput = true,
+ tokensPerItem,
+ language,
+ splitOnWord,
+ signal,
+ onProgress,
}: {
- inputPath: string;
- whisperPath: string;
- model: WhisperModel;
- tokenLevelTimestamps: HasTokenLevelTimestamps;
- modelFolder?: string;
- translateToEnglish?: boolean;
- printOutput?: boolean;
- tokensPerItem?: true extends HasTokenLevelTimestamps ? never : number | null;
- language?: Language | null;
- splitOnWord?: boolean;
- signal?: AbortSignal;
- onProgress?: TranscribeOnProgress;
+ inputPath: string;
+ whisperPath: string;
+ whisperCppVersion: string;
+ model: WhisperModel;
+ tokenLevelTimestamps: HasTokenLevelTimestamps;
+ modelFolder?: string;
+ translateToEnglish?: boolean;
+ printOutput?: boolean;
+ tokensPerItem?: true extends HasTokenLevelTimestamps ? never : number | null;
+ language?: Language | null;
+ splitOnWord?: boolean;
+ signal?: AbortSignal;
+ onProgress?: TranscribeOnProgress;
}): Promise<TranscriptionJson<HasTokenLevelTimestamps>> => {
- if (!existsSync(whisperPath)) {
- throw new Error(
- `Whisper does not exist at ${whisperPath}. Double-check the passed whisperPath. If you havent installed whisper, check out the installWhisperCpp() API at https://www.remotion.dev/docs/install-whisper-cpp/install-whisper-cpp to see how to install whisper programatically.`,
- );
- }
-
- if (!existsSync(inputPath)) {
- throw new Error(`Input file does not exist at ${inputPath}`);
- }
-
- if (!isWavFile(inputPath)) {
- throw new Error(
- 'Invalid inputFile type. The provided file is not a wav file! Convert the file to a 16KHz wav file first: "ffmpeg -i input.mp4 -ar 16000 output.wav -y"',
- );
- }
-
- const tmpJSONDir = path.join(process.cwd(), 'tmp');
-
- const {outputPath: tmpJSONPath} = await transcribeToTemporaryFile({
- fileToTranscribe: inputPath,
- whisperPath,
- model,
- tmpJSONPath: tmpJSONDir,
- modelFolder: modelFolder ?? null,
- translate: translateToEnglish,
- tokenLevelTimestamps,
- printOutput,
- tokensPerItem: tokenLevelTimestamps ? 1 : (tokensPerItem ?? 1),
- language: language ?? null,
- signal: signal ?? null,
- splitOnWord: splitOnWord ?? null,
- onProgress: onProgress ?? null,
- });
-
- const json = (await readJson(
- tmpJSONPath,
- )) as TranscriptionJson<HasTokenLevelTimestamps>;
- fs.unlinkSync(tmpJSONPath);
-
- return json;
+ if (!existsSync(whisperPath)) {
+ throw new Error(
+ `Whisper does not exist at ${whisperPath}. Double-check the passed whisperPath. If you havent installed whisper, check out the installWhisperCpp() API at https://www.remotion.dev/docs/install-whisper-cpp/install-whisper-cpp to see how to install whisper programatically.`,
+ );
+ }
+
+ if (!existsSync(inputPath)) {
+ throw new Error(`Input file does not exist at ${inputPath}`);
+ }
+
+ if (!isWavFile(inputPath)) {
+ throw new Error(
+ 'Invalid inputFile type. The provided file is not a wav file! Convert the file to a 16KHz wav file first: "ffmpeg -i input.mp4 -ar 16000 output.wav -y"',
+ );
+ }
+
+ const tmpJSONDir = path.join(process.cwd(), 'tmp');
+
+ const {outputPath: tmpJSONPath} = await transcribeToTemporaryFile({
+ fileToTranscribe: inputPath,
+ whisperPath,
+ whisperCppVersion,
+ model,
+ tmpJSONPath: tmpJSONDir,
+ modelFolder: modelFolder ?? null,
+ translate: translateToEnglish,
+ tokenLevelTimestamps,
+ printOutput,
+ tokensPerItem: tokenLevelTimestamps ? 1 : (tokensPerItem ?? 1),
+ language: language ?? null,
+ signal: signal ?? null,
+ splitOnWord: splitOnWord ?? null,
+ onProgress: onProgress ?? null,
+ });
+
+ const json = (await readJson(
+ tmpJSONPath,
+ )) as TranscriptionJson<HasTokenLevelTimestamps>;
+ fs.unlinkSync(tmpJSONPath);
+
+ return json;
};
diff --git a/packages/install-whisper-cpp/src/utils.ts b/packages/install-whisper-cpp/src/utils.ts
new file mode 100644
index 0000000000..b31f8b4939
--- /dev/null
+++ b/packages/install-whisper-cpp/src/utils.ts
@@ -0,0 +1,36 @@
+/**
+ * Compares two version strings.
+ *
+ * @param version1 - The first version string.
+ * @param version2 - The second version string.
+ * @returns 1 if version1 > version2, -1 if version1 < version2, 0 if they are equal.
+ * @throws {Error} If either version is not a valid string or has an invalid format.
+ */
+export function compareVersions(version1: string, version2: string): number {
+ const parseVersion = (version: string): number[] => {
+ const parts = version.split('.').map((part) => Number(part));
+ if (parts.some(isNaN)) {
+ throw new Error('Invalid version format. Expected x.x.x');
+ }
+ return parts;
+ };
+
+ if (typeof version1 !== 'string' || typeof version2 !== 'string') {
+ throw new Error('Both inputs should be strings. Expected x.x.x');
+ }
+
+ const v1Parts = parseVersion(version1);
+ const v2Parts = parseVersion(version2);
+
+ // Ensure both versions have the same number of parts
+ const maxLength = Math.max(v1Parts.length, v2Parts.length);
+ while (v1Parts.length < maxLength) v1Parts.push(0);
+ while (v2Parts.length < maxLength) v2Parts.push(0);
+
+ for (let i = 0; i < maxLength; i++) {
+ if (v1Parts[i] > v2Parts[i]) return 1; // Version1 is greater
+ if (v1Parts[i] < v2Parts[i]) return -1; // Version2 is greater
+ }
+
+ return 0; // Versions are equal
+}