whisper-node

repository·master·Indexed 43 days ago

https://github.com/ariym/whisper-node

Node.js bindings for OpenAI's Whisper model providing local, CPU-optimized audio transcription. Version 1.1.2 supports various architectures including Apple Silicon and requires .wav files sampled at 16Hz. It includes a CLI for downloading models and functions for transcribing audio, parsing VTT strings, and configuring whisper.cpp flags such as language detection and word-level timestamps.

Tokens
2.5K
Snippets
11
Records
11
Agent score
54%

What's inside whisper-node

  1. Install whisper-node

    master

    To use whisper-node in your project, install the package via npm.

    Windows Requirement: You must install the make command (e.g., from GNUWin32) to ensure successful compilation/operation.

    Optional: Download Models You can pre-download a Whisper model using the provided CLI command:

    npx whisper-node download
    npm install whisper-node
  2. Transcribe audio with whisper()

    master

    The primary way to use the library is by calling the whisper function with a file path. By default, it returns an array of objects containing timestamps and the transcribed text.

    Input Requirements:

    • Files must be in .wav format.
    • Audio must be sampled at 16Hz (16000Hz).

    If you have an .mp3, you can convert it using FFmpeg:

    ffmpeg -i input.mp3 -ar 16000 output.wav
    import whisper from 'whisper-node';
    
    const transcript = await whisper("example/sample.wav");
    
    console.log(transcript); // output: [ {start,end,speech} ]
  3. Configure whisper() options

    master

    The whisper function accepts an optional options object to control model selection and transcription behavior.

    Top-level Options

    • modelName: The name of the model to use (e.g., base.en). Defaults to base.en.
    • modelPath: A custom path to a .bin model file. Note: You cannot use modelPath and modelName together.

    whisperOptions

    Nested within the options object, these control the underlying Whisper engine:

    • language: The language to transcribe. Use 'auto' (default) for automatic detection.
    • gen_file_txt: Boolean. If true, outputs a .txt file.
    • gen_file_subtitle: Boolean. If true, outputs an .srt file.
    • gen_file_vtt: Boolean. If true, outputs an .vtt file.
    • word_timestamps: Boolean. If true, provides timestamps for every individual word. Note: When word_timestamps is true, you cannot use timestamp_size.
    import whisper from 'whisper-node';
    
    const filePath = "example/sample.wav";
    
    const options = {
      modelName: "base.en",
      whisperOptions: {
        language: 'auto',
        gen_file_txt: false,
        gen_file_subtitle: false,
        gen_file_vtt: false,
        word_timestamps: true
      }
    }
    
    const transcript = await whisper(filePath, options);
  4. Configure whisper-node options

    master

    When calling whisper(), you can provide an IOptions object to customize the transcription process.

    Available keys:

    • modelName (string, optional): The name of the model stored within the package's internal directory (node_modules/whisper-node/lib/whisper.cpp/models).
    • modelPath (string, optional): A custom filesystem path to a specific model file.
    • whisperOptions (IFlagTypes, optional): A set of flags passed directly to the underlying whisper.cpp command.
    • shellOptions (IShellOptions, optional): Configuration for the shell execution environment.
    interface IOptions {
      modelName?: string,
      modelPath?: string,
      whisperOptions?: IFlagTypes,
      shellOptions?: IShellOptions
    }
  5. Understand the JSON transcript output format

    master

    The whisper function returns a Promise that resolves to an array of objects. Each object represents a segment of speech with the following structure:

    • start: A string representing the start timestamp (e.g., "00:00:14.310").
    • end: A string representing the end timestamp (e.g., "00:00:16.480").
    • speech: The transcribed text string.
    [
      {
        "start":  "00:00:14.310",
        "end":    "00:00:16.480",
        "speech": "howdy"
      }
    ]
  6. Generate a whisper.cpp command with createCppCommand

    master

    The createCppCommand function generates a shell command string compatible with whisper.cpp. It requires a filePath (the audio file to transcribe) and allows you to specify a model via modelName or modelPath, along with various transcription options.

    Constraints:

    • You must provide either modelName or modelPath. Providing both will throw an error.
    • If no model is provided, the library attempts to use the DEFAULT_MODEL.
    • If using a modelName, the model must be present in the ./models/ directory (otherwise, you must run npx whisper-node download).
    const command = createCppCommand({
      filePath: './audio.wav',
      modelName: 'base',
      options: {
        language: 'en',
        gen_file_txt: true
      }
    });
    // Resulting string example: `./main -l en -otxt -m ./models/ggml-base.bin -f ./audio.wav`
  7. Transcribe audio files with whisper()

    master

    The whisper function is the primary entrypoint for transcribing audio files using the whisper.cpp engine. It accepts a file path to the audio and an optional configuration object. The function returns a Promise that resolves to an array of ITranscriptLine objects, where each object contains the start time, end time, and the transcribed speech text.

    Returns: Promise<ITranscriptLine[]> where ITranscriptLine is {start, end, speech}.

    import { whisper } from 'whisper-node';
    
    const transcript = await whisper('path/to/audio.mp3', {
      modelName: 'base',
      whisperOptions: {
        // ... whisper.cpp flags
      }
    });
    
    console.log(transcript); // [{ start: 0, end: 2, speech: 'Hello world' }, ...]
  8. Parse VTT transcript strings with parseTranscript()

    master

    The parseTranscript function converts a VTT-formatted transcript string into an array of ITranscriptLine objects. It expects lines in the format [start_timestamp --> end_timestamp] speech_content.

    Note that the parser relies on a specific delimiter: a timestamp enclosed in brackets followed by exactly two spaces (] ) before the speech content. It also strips newlines and leading spaces from the speech text.

    import parseTranscript from './src/tsToArray';
    
    const vttContent = "[00:00:01.000 --> 00:00:04.000]  Hello world\n";
    const transcript = parseTranscript(vttContent);
    // Result: [{ start: '00:00:01.000', end: '00:00:04.000', speech: 'Hello world' }]
  9. Configure transcription options via IFlagTypes

    master

    When calling createCppCommand, you can pass an options object of type IFlagTypes to control the output format and transcription behavior. These options map directly to whisper.cpp flags.

    Available Options:

    • gen_file_txt (boolean): Generates a .txt output file (-otxt).
    • gen_file_subtitle (boolean): Generates an .srt subtitle file (-osrt).
    • gen_file_vtt (boolean): Generates a .vtt subtitle file (-ovtt).
    • language (string): Specifies the input language code (e.g., 'en') (-l).
    • timestamp_size (number): Sets the timestamp granularity (-ml).
    • word_timestamps (boolean): Enables word-level timestamps (shorthand for timestamp_size: 1).

    Constraint: You cannot use timestamp_size and word_timestamps simultaneously. You must choose one.

    const options: IFlagTypes = {
      gen_file_txt: true,
      gen_file_subtitle: true,
      language: 'en',
      word_timestamps: true
    };
  10. Available model names in MODELS_LIST

    master

    The library provides a predefined list of model names that map to specific ggml binary files. If you use these names, the library expects the files to exist in the ./models/ directory.

    modelNamefilename
    tinyggml-tiny.bin
    tiny.enggml-tiny.en.bin
    baseggml-base.bin
    base.enggml-base.en.bin
    smallggml-small.bin
    small.enggml-small.en.bin
    mediumggml-medium.bin
    medium.enggml-medium.en.bin
    large-v1ggml-large-v1.bin
    largeggml-large.bin
    export const MODELS_LIST = {
      "tiny": "ggml-tiny.bin",
      "tiny.en": "ggml-tiny.en.bin",
      "base": "ggml-base.bin",
      "base.en": "ggml-base.en.bin",
      "small": "ggml-small.bin",
      "small.en": "ggml-small.en.bin",
      "medium": "ggml-medium.bin",
      "medium.en": "ggml-medium.en.bin",
      "large-v1": "ggml-large-v1.bin",
      "large": "ggml-large.bin"
    }
  11. ITranscriptLine data structure

    master

    The ITranscriptLine type defines the shape of an individual segment in a parsed transcript. Each object contains the timing information and the transcribed text.

    type ITranscriptLine = {
      start: string;
      end: string;
      speech: string;
    }