whisper_streaming

repository·main·Indexed 25 days ago

https://github.com/ufal/whisper_streaming

A real-time speech-to-text transcription and translation system built on Whisper models. It utilizes a local agreement policy with self-adaptive latency for high-quality streaming. The system supports multiple backends including faster-whisper, whisper-timestamped, OpenAI Whisper API, and Whisper MLX, and provides a Python module via OnlineASRProcessor for application integration.

Tokens
2.7K
Snippets
7
Records
9
Agent score
37%

What's inside whisper_streaming

  1. Install Whisper backends

    main

    The project supports several backends. You only need to install the one you intend to use:

    1. faster-whisper (Recommended): Best for GPU support. Requires NVIDIA libraries (e.g., CUDNN 8.5.0 and CUDA 11.7).
      pip install faster-whisper
    
    2. **whisper-timestamped**: A slower, less restrictive alternative.
       ```bash
    pip install git+https://github.com/linto-ai/whisper-timestamped
    1. OpenAI Whisper API: Fast, requires no GPU, but incurs costs. Requires setting the OPENAI_API_KEY environment variable.
      pip install openai
      export OPENAI_API_KEY=sk-xxx
    
    4. **Whisper MLX**: Optimized for Apple Silicon (M1, M2, etc.).
       ```bash
    pip install mlx-whisper
  2. Run a real-time microphone server with whisper_online_server.py

    main

    The whisper_online_server.py script allows you to run a TCP server that accepts real-time audio from a microphone. It supports all the same model and processing options as whisper_online.py, plus --host, --port, and --warmup-file.

    Client Example (Linux/macOS): Use arecord to capture raw 16kHz mono S16_LE audio and pipe it to nc (netcat) connected to your server.

    arecord -f S16_LE -c1 -r 16000 -t raw -D default | nc localhost 43001
  3. Install sentence segmenters (Optional)

    main

    If you choose to use the sentence buffer trimming option (which trims at the end of confirmed sentences), you must install a language-specific segmenter:

    • For supported languages (as, bn, ca, cs, de, el, en, es, et, fi, fr, ga, gu, hi, hu, is, it, kn, lt, lv, ml, mni, mr, nl, or, pa, pl, pt, ro, ru, sk, sl, sv, ta, te, yue, zh):
      pip install opus-fast-mosestokenizer
    
    - **For Ukrainian (`uk`)**:
      ```bash
    pip install tokenize_uk
    • For other languages (using wtpsplit):
      pip install torch wtpsplit
    
    *Note: If you encounter installation issues with `opus-fast-mosestokenizer` on Windows or Mac, use the default `segment` option instead.*
    
  4. Use whisper_streaming as a Python module

    main

    To integrate streaming ASR into your own application, use the OnlineASRProcessor and an ASR backend (like FasterWhisperASR).

    Core Workflow:

    1. Initialize the ASR backend (e.g., FasterWhisperASR).
    2. Create an OnlineASRProcessor instance with that backend.
    3. In your audio loop, call insert_audio_chunk(audio_data).
    4. Call process_iter() to get the current partial/confirmed transcript.
    5. Call finish() at the end of the stream to get the final output.
    6. Use init() if you intend to reuse the processor object for a new audio stream.
    from whisper_online import *
    
    src_lan = "en"  # source language
    tgt_lan = "en"  # target language  -- same as source for ASR, "en" if translate task is used
    
    asr = FasterWhisperASR(lan, "large-v2")  # loads and wraps Whisper model
    # set options:
    # asr.set_translate_task()  # it will translate from lan into English
    # asr.use_vad()  # set using VAD
    
    online = OnlineASRProcessor(asr)  # create processing object with default buffer trimming option
    
    while audio_has_not_ended:
    	# receive new audio chunk (and e.g. wait for min_chunk_size seconds first, ...)
    	a = ... 
    	online.insert_audio_chunk(a)
    	o = online.process_iter()
    	print(o) # do something with current partial output
    
    # at the end of this audio processing
    o = online.finish()
    print(o)  # do something with the last output
    
    
    online.init()  # refresh if you're going to re-use the object for the next audio
  5. Reference: whisper_online.py CLI options

    main

    Command-line arguments for simulating real-time audio processing from a file.

    positional arguments:
      audio_path            Filename of 16kHz mono channel wav, on which live streaming is simulated.
    
    options:
      -h, --help            show this help message and exit
      --min-chunk-size MIN_CHUNK_SIZE
                            Minimum audio chunk size in seconds. It waits up to this time to do processing. If the processing takes shorter time, it waits, otherwise it processes the whole segment that was
                            received by this time.
      --model {tiny.en,tiny,base.en,base,small.en,small,medium.en,medium,large-v1,large-v2,large-v3,large,large-v3-turbo}
                            Name size of the Whisper model to use (default: large-v2). The model is automatically downloaded from the model hub if not present in model cache dir.
      --model_cache_dir MODEL_CACHE_DIR
                            Overriding the default model cache dir where models downloaded from the hub are saved
      --model_dir MODEL_DIR
                            Dir where Whisper model.bin and other files are saved. This option overrides --model and --model_cache_dir parameter.
      --lan LAN, --language LAN
                            Source language code, e.g. en,de,cs, or 'auto' for language detection.
      --task {transcribe,translate}
                            Transcribe or translate.
      --backend {faster-whisper,whisper_timestamped,openai-api}
                            Load only this backend for Whisper processing.
      --vac                 Use VAC = voice activity controller. Recommended. Requires torch.
      --vac-chunk-size VAC_CHUNK_SIZE
                            VAC sample size in seconds.
      --vad                 Use VAD = voice activity detection, with the default parameters.
      --buffer_trimming {sentence,segment}
                            Buffer trimming strategy -- trim completed sentences marked with punctuation mark and detected by sentence segmenter, or the completed segments returned by Whisper. Sentence segmenter
                            must be installed for "sentence" option.
      --buffer_trimming_sec BUFFER_TRIMMING_SEC
                            Buffer trimming length threshold in seconds. If buffer length is longer, trimming sentence/segment is triggered.
      -l {DEBUG,INFO,WARNING,ERROR,CRITICAL}, --log-level {DEBUG,INFO,WARNING,ERROR,CRITICAL}
                            Set the log level
      --start_at START_AT   Start processing audio at this time.
      --offline             Offline mode.
      --comp_unaware        Computationally unaware simulation.
  6. Understand the output format

    main

    The streaming output follows a specific format where each line represents a transcript update with timestamps and text:

    [Timestamp_Start] [Start_Sample] [End_Sample] [Text]

    Example:

    2691.4399 300 1380 Chairman, thank you.
    6914.5501 1940 4940 If the debate today had a
  7. Simulate real-time processing from an audio file using whisper_online.py

    main

    You can simulate real-time streaming using a pre-recorded 16kHz mono channel WAV file via the whisper_online.py CLI.

    Simulation Modes:

    • Default: Real-time simulation, computationally aware. The chunk size is MIN_CHUNK_SIZE or larger depending on processing time.
    • --comp_unaware**: Computationally unaware simulation. The timer stops during model computation, ensuring the chunk size is always exactly MIN_CHUNK_SIZE. Use this to find the lower bound for latency.
    • --start_at START_AT**: Starts processing at a specific timestamp in the audio file. Useful for debugging specific segments.
    • --offline**: Processes the entire file at once to find the lowest possible Word Error Rate (WER).
    python3 whisper_online.py en-demo16.wav --language en --min-chunk-size 1 > out.txt