parakeet-mlx

repository·master·Indexed 21 days ago

https://github.com/senstella/parakeet-mlx

An implementation of Nvidia's Parakeet Automatic Speech Recognition (ASR) models optimized for Apple Silicon using the MLX framework. It provides a CLI for transcribing audio files into formats like SRT, VTT, and JSON, as well as a Python API for high-level transcription, streaming ASR, and low-level log-mel spectrum processing. Supported architectures include CTC, RNNT, TDT, and TDT-CTC.

Tokens
9.3K
Snippets
27
Records
35
Agent score
75%

What's inside parakeet-mlx

  1. Understand Transcription Result Data Structures

    master

    The transcription results are returned in a hierarchical structure providing varying levels of granularity.

    AlignedResult (Top-level)

    • text: The full transcribed text string.
    • sentences: A list of AlignedSentence objects.

    AlignedSentence (Sentence-level)

    • text: The text of the sentence.
    • start: Start time in seconds.
    • end: End time in seconds.
    • duration: The duration of the sentence (end - start).
    • tokens: A list of AlignedToken objects.

    AlignedToken (Word/Token-level)

    • text: The token text.
    • start: Start time in seconds. | end: End time in seconds.
    • duration: The duration of the token.
  2. Install parakeet-mlx

    master

    Parakeet MLX is an implementation of Nvidia's Parakeet ASR models for Apple Silicon using MLX.

    Prerequisite: Ensure ffmpeg is installed on your system for the CLI to function correctly.

    To add as a dependency:

    uv add parakeet-mlx -U

    To install as a standalone CLI tool:

    uv tool install parakeet-mlx -U

    Using pip

    pip install parakeet-mlx -U
    uv add parakeet-mlx -U
  3. Implement TDT, RNNT, and CTC models

    master

    Parakeet provides three main model architectures implemented as subclasses of BaseParakeet:

    • ParakeetTDT: Uses Token-and-Duration Transducer (TDT) decoding. Supports both Greedy and Beam decoding. Requires ParakeetTDTArgs.
    • ParakeetRNNT: Uses Recurrent Neural Network Transducer (RNNT) decoding. Currently only supports Greedy decoding. Requires ParakeetRNNTArgs.
    • ParakeetCTC: Uses Connectionist Temporal Classification (CTC) decoding. Requires ParakeetCTCArgs.
    • ParakeetTDTCTC: A hybrid model that uses TDT for generation but includes an auxiliary CTC decoder.
  4. Perform Streaming Transcription

    master

    For real-time transcription, use the transcribe_stream context manager. This allows you to feed audio chunks into the model and access both finalized and draft tokens.

    from parakeet_mlx import from_pretrained
    from parakeet_mlx.audio import load_audio
    import numpy as np
    
    model = from_pretrained("mlx-community/parakeet-tdt-0.6b-v3")
    
    # context_size: (left_context, right_context) frames
    with model.transcribe_stream(context_size=(256, 256)) as transcriber:
        audio_data = load_audio("audio_file.wav", model.preprocessor_config.sample_rate)
        chunk_size = model.preprocessor_config.sample_rate  # 1 second chunks
    
        for i in range(0, len(audio_data), chunk_size):
            chunk = audio_data[i:i+chunk_size]
            transcriber.add_audio(chunk)
    
            result = transcriber.result
            print(f"Current text: {result.text}")
            # Use transcriber.finalized_tokens or transcriber.draft_tokens for granular access

    Streaming Parameters

    • context_size: Tuple of (left_context, right_context) frames. Controls the attention window.
    • depth: Number of encoder layers that preserve exact computation across chunks. Higher depth increases computational consistency with non-streaming mode. Default is 1.
    • keep_original_attention: Boolean. If False (recommended), switches to local attention for streaming. If True, keeps original attention.
    with model.transcribe_stream(context_size=(256, 256)) as transcriber:
        transcriber.add_audio(chunk)
        print(transcriber.result.text)
  5. Use the parakeet-mlx Python API

    master

    The Python API provides several ways to interact with the models, from high-level transcription to low-level log-mel processing.

    Basic Transcription

    Use from_pretrained to load a model and .transcribe() to get results.

    from parakeet_mlx import from_pretrained
    
    model = from_pretrained("mlx-community/parakeet-tdt-0.6b-v3")
    result = model.transcribe("audio_file.wav")
    
    print(result.text)

    Accessing Timestamps

    The result.sentences attribute returns a list of AlignedSentence objects containing timing information.

    from parakeet_mlx import from_pretrained
    
    model = from_pretrained("mlx-community/parakeet-tdt-0.6b-v3")
    result = model.transcribe("audio_file.wav")
    
    # Returns [AlignedSentence(text="...", start=..., end=..., duration=..., tokens=[...])]
    print(result.sentences)

    Advanced Transcription Configurations

    Chunking

    For long audio files, specify chunk_duration and overlap_duration.

    result = model.transcribe("audio_file.wav", chunk_duration=120.0, overlap_duration=15.0)

    Beam Decoding

    Requires DecodingConfig and Beam (though Beam is often implied by the config structure).

    from parakeet_mlx import from_pretrained, DecodingConfig
    
    model = from_pretrained("mlx-community/parakeet-tdt-0.6b-v3")
    config = DecodingConfig(
        decoding={"beam_size": 5, "length_penalty": 0.013, "patience": 3.5, "duration_reward": 0.67}
    )
    result = model.transcribe("audio_file.wav", decoding_config=config)

    Sentence Splitting

    Control how sentences are segmented using SentenceConfig.

    from parakeet_mlx import from_pretrained, DecodingConfig, SentenceConfig
    
    model = from_pretrained("mlx-community/parakeet-tdt-0.6b-v3")
    config = DecodingConfig(
        sentence=SentenceConfig(max_words=30, silence_gap=5.0, max_duration=40.0)
    )
    result = model.transcribe("audio_file.wav", decoding_config=config)

    Local Attention

    To reduce memory usage for long audio, switch the attention model.

    model.encoder.set_attention_model("rel_pos_local_attn", (256, 256))
    result = model.transcribe("audio_file.wav")
    from parakeet_mlx import from_pretrained
    
    model = from_pretrained("mlx-community/parakeet-tdt-0.6b-v3")
    result = model.transcribe("audio_file.wav")
    print(result.text)
  6. Low-Level API: Transcribe Log-Mel Spectrums

    master

    If you have already preprocessed your audio into a log-mel spectrum, you can bypass the standard transcribe method and use model.generate directly.

    import mlx.core as mx
    from parakeet_mlx.audio import get_logmel, load_audio
    from parakeet_mlx import DecodingConfig
    
    # Load and preprocess audio manually
    audio = load_audio("audio.wav", model.preprocessor_config.sample_rate)
    mel = get_logmel(audio, model.preprocessor_config)
    
    # Generate transcription with alignments
    # Accepts [batch, sequence, feat] or [sequence, feat]
    # Returns a list of AlignedResult objects
    alignments = model.generate(mel, decoding_config=DecodingConfig())
    mel = get_logmel(audio, model.preprocessor_config)
    alignments = model.generate(mel, decoding_config=DecodingConfig())
  7. Configure decoding behavior with DecodingConfig

    master

    The DecodingConfig class controls how the model decodes the acoustic features into text. It supports two primary modes:

    1. Greedy Decoding: Uses the Greedy class. Fast, but less accurate as it picks the single most likely token at each step.
    2. Beam Search: Uses the Beam class. More accurate, exploring multiple hypotheses simultaneously.

    Beam Configuration Options:

    • beam_size (int): Number of hypotheses to maintain (default: 5).
    • length_penalty (float): Penalty applied to longer sequences (default: 1.0).
    • patience (float): Controls how long the beam search continues (default: 1.0).
    • duration_reward (float): TDT-only parameter to reward duration predictions (default: 0.7).
    from parakeet_mlx import DecodingConfig, Beam, Greedy
    
    # For Beam Search
    config = DecodingConfig(decoding=Beam(beam_size=10, length_penalty=0.5))
    
    # For Greedy Search
    config = DecodingConfig(decoding=Greedy())
  8. Reference: parakeet-mlx CLI Options

    master

    The following options are available for the parakeet-mlx CLI. Many can also be set via environment variables.

    OptionDefaultEnv VarDescription
    --modelmlx-community/parakeet-tdt-0.6b-v3PARAKEET_MODELHugging Face repository of the model
    --output-dircurrent directoryDirectory to save outputs
    --output-formatsrtPARAKEET_OUTPUT_FORMATtxt, srt, vtt, json, or all
    --output-template{filename}PARAKEET_OUTPUT_TEMPLATESupports {parent}, {filename}, {index}, {date}
    --highlight-wordsFalseEnable word-level timestamps in SRT/VTT
    --verbose / -vFalsePrint detailed progress
    --decodinggreedyPARAKEET_DECODINGgreedy or beam (beam only for TDT models)
    --chunk-duration120PARAKEET_CHUNK_DURATIONSeconds for long audio chunking (0 to disable)
    --overlap-duration15PARAKEET_OVERLAP_DURATIONOverlap seconds if chunking
    --beam-size5PARAKEET_BEAM_SIZEBeam size (only for beam decoding)
    --length-penalty0.013PARAKEET_LENGTH_PENALTYLength penalty in beam (0.0 to disable)
    --patience3.5PARAKEET_PATIENCEPatience in beam (1.0 to disable)
    --duration-reward0.67PARAKEET_DURATION_REWARD0.0 to 1.0; <0.5 favors logprobs, >0.5 favors duration
    --max-wordsNonePARAKEET_MAX_WORDSMax words per sentence
    --silence-gapNoneSplit sentence if it exceeds this gap (seconds)
    --max-durationNoneMax sentence duration (seconds)
    --fp32 / --bf16bf16PARAKEET_FP32Precision to use
    --full-attention / --local-attentionfull-attentionPARAKEET_LOCAL_ATTENTIONUse full or local attention (local reduces memory)
    --local-attention-context-size256PARAKEET_LOCAL_ATTENTION_CTXLocal attention window in frames
    --cache-dirNonePARAKEET_CACHE_DIRHuggingFace model cache directory
  9. Use the parakeet-mlx CLI

    master

    The CLI allows you to transcribe audio files from the terminal.

    Usage: parakeet-mlx <audio_files> [OPTIONS]

    Arguments:

    • audio_files: One or more audio files (WAV, MP3, etc.) to transcribe.

    Common Examples:

    Basic transcription:

    parakeet-mlx audio.mp3

    Multiple files with word-level timestamps (VTT format):

    parakeet-mlx *.mp3 --output-format vtt --highlight-words

    Generate all supported output formats (txt, srt, vtt, json):

    parakeet-mlx audio.mp3 --output-format all
    parakeet-mlx audio.mp3
  10. Data structures for transcription alignment

    master

    The parakeet_mlx.alignment module provides several dataclasses to represent structured transcription results, moving from individual tokens to full sentences and complete results.

    • AlignedToken: Represents a single word or unit of speech.
    • AlignedSentence: A collection of AlignedToken objects representing a sentence. It automatically calculates its own start, end, duration, and an aggregate confidence score (using the geometric mean of token confidences).
    • AlignedResult: The top-level object containing the full transcribed text and a list of AlignedSentence objects. It provides a .tokens property to flatten all tokens from all sentences into a single list.
    from parakeet_mlx.alignment import AlignedToken, AlignedSentence, AlignedResult
    
    # Example of the hierarchy
    token = AlignedToken(id=1, text="Hello", start=0.0, duration=0.5, confidence=0.9)
    sentence = AlignedSentence(text="Hello world.", tokens=[token, ...])
    result = AlignedResult(text="Hello world.", sentences=[sentence])
    
    # Accessing all tokens in a result
    all_tokens = result.tokens
  11. Generate log-Mel spectrograms with get_logmel

    master

    The get_logmel function transforms a raw audio MLX array into a log-Mel spectrogram based on the provided PreprocessArgs.

    Workflow:

    1. Padding: If args.pad_to is set, the audio is padded to that length.
    2. Pre-emphasis: If args.preemph is provided, it applies a high-pass filter.
    3. STFT: Applies a Short-Time Fourier Transform using the specified window type (hann, hamming, blackman, or bartlett).
    4. Mel Filterbank: Applies Mel filterbanks to the magnitude spectrum.
    5. Log Scaling: Applies a log transform.
    6. Normalization: Normalizes the output based on args.normalize (either "per_feature" or global normalization).

    Returns an MLX array with shape (1, n_mels, time).

    import mlx.core as mx
    from parakeet_mlx.audio import load_audio, get_logmel, PreprocessArgs
    
    # 1. Setup args
    args = PreprocessArgs(
        sample_rate=16000,
        normalize="per_feature",
        window_size=0.02,
        window_stride=0.01,
        window="hann",
        features=80,
        n_fft=400,
        dither=0.0
    )
    
    # 2. Load audio
    audio = load_audio("path/to/audio.wav", sampling_rate=16000)
    
    # 3. Get log-mel spectrogram
    log_mel = get_logmel(audio, args)
  12. Access alignment results and types

    master

    When performing alignment tasks, the library exports the following types to represent the structure of the transcribed text and its timing:

    • AlignedResult: The top-level container for alignment output.
    • AlignedSentence: Represents a single sentence with timing information (start, end, duration) and a list of tokens.
    • AlignedToken: Represents individual word or sub-word tokens within a sentence.
    • SentenceConfig: Configuration settings for sentence-level alignment.