RealtimeSTT

repository·master·Indexed 27 days ago

https://github.com/koljab/realtimestt

A Python library for high-performance, real-time speech-to-text applications. It supports voice activity detection (VAD), wake words, and multiple transcription engines including faster-whisper, Kroko-ONNX, and Parakeet. The library provides an AudioToTextRecorder for microphone or external audio input and includes a FastAPI WebSocket server for browser-based transcription with multi-user session isolation.

Tokens
43.8K
Snippets
107
Records
226
Agent score
94%

What's inside RealtimeSTT

  1. Understand RealtimeSTT Licensing

    master

    RealtimeSTT is released under the MIT license. However, the project integrates various optional transcription (ASR), Voice Activity Detection (VAD), and wake-word engines. Each of these engines brings its own dependencies, model weights, and service terms which are independent of RealtimeSTT.

    Key considerations for developers:

    • Upstream Terms: Always review the specific license for the engine, model revision, and distribution path you are using (e.g., Hugging Face model cards, API terms, or package metadata).
    • Redistribution: If you bundle binaries, wheels, model files, or Docker images, you must preserve all upstream copyright notices and license texts.
    • Model vs. Runtime: Be aware that the runtime code (e.g., a Python package) and the model weights it loads may have different licenses.
    • Commercial Use: While many engines are permissive, always verify if the specific model or service provider (like Kroko or Picovoice) requires a commercial license for production use.
  2. Understand the RealtimeSTT Audio Pipeline

    master

    RealtimeSTT operates around a recorder-centered audio pipeline. The internal audio currency is 16 kHz mono PCM. The data flow follows this sequence:

    1. Audio Input: Provided via microphone or feed_audio().
    2. AudioToTextRecorder: Manages an audio queue.
    3. Gating: Processes wake word, VAD (Voice Activity Detection), pre-roll, and recording state.
    4. Realtime ASR: Optional realtime ASR and text stabilization.
    5. Final ASR Engine: The core transcription engine.
    6. Output: Dispatched via callbacks, client/server messages, or the text() return value.
  3. Configure Moonshine model cache directory

    master

    The Transformers backend automatically downloads model and processor files from Hugging Face. You can specify where these are stored using the download_root parameter, which is passed as cache_dir during loading.

    recorder = AudioToTextRecorder(
        transcription_engine="moonshine",
        model="UsefulSensors/moonshine-streaming-medium",
        download_root="models/hf",
        language="en",
    )
  4. Install and use the CPU-friendly whisper.cpp engine

    master

    For local testing on CPUs, install the whisper-cpp extra and configure the transcription_engine to "whisper_cpp".

    python -m pip install "RealtimeSTT[whisper-cpp]"
    from RealtimeSTT import AudioToTextRecorder
    
    if __name__ == "__main__":
        recorder = AudioToTextRecorder(
            transcription_engine="whisper_cpp",
            model="tiny.en",
            device="cpu",
            beam_size=1,
        )
        print(recorder.text())
        recorder.shutdown()
  5. Design a Multi-User FastAPI Transcription Server

    master

    To transform a single-session example_fastapi_server into a multi-user system, you must decouple per-session state from shared inference resources. Do not simply remove the single-client guard, as this will cause audio from different users to enter the same recorder and leak transcriptions between users.

    1. Per-Session State

    Each session must maintain its own independent state, including:

    • sessionId and optional authenticated user ID
    • WebSocket connection
    • Transcript segment IDs
    • VAD/recording state (including separate WebRTC/Silero runtime state per stream)
    • Audio ring buffer or bounded audio queue
    • Realtime scheduling state and final-transcription state
    • Per-session quotas, drop counters, and latency metrics

    2. Shared Inference Resources

    To avoid duplicating VRAM and startup costs, use shared resources instead of one recorder per user:

    • One shared final transcription model (or a small worker pool)
    • Optionally one shared realtime model
    • A fair scheduler and global admission control

    Note on VAD: WebRTC and Silero VAD keep stream-local activity state. The safe baseline is to maintain one VAD state machine per accepted session to avoid mixing user activity states.

  6. Run API Compatibility Tests

    master

    If you are modifying the recorder API, run the following unit tests to validate compatibility across different audio fixtures and backends:

    python -m pytest tests\unit\test_audio_fixtures.py
    python -m pytest tests\unit\test_slow_final_transcription_audio_gap.py
    python -m pytest tests\unit\test_silero_vad_backend.py
    python -m pytest tests\unit\test_realtime_text_stabilizer.py
    python -m pytest tests\unit\test_realtime_streaming_transcription.py
    python -m pytest tests\unit\test_fastapi_server_protocol.py
    python -m pytest tests\unit\test_fastapi_server_multi_user.py
    python -m pytest tests\unit\test_audio_fixtures.py
  7. Install the faster-whisper engine

    master

    To use faster_whisper (the default transcription engine) with RealtimeSTT, install the specific extra via pip.

    If installing as a package:

    pip install "RealtimeSTT[faster-whisper]"

    If installing from a source checkout:

    python -m pip install -e ".[faster-whisper]"
    pip install "RealtimeSTT[faster-whisper]"
  8. Deploy the FastAPI Server

    master

    Follow these best practices for deploying the RealtimeSTT FastAPI server:

    • OS/Runtime: Use Linux or WSL2 for CUDA-heavy engines (Parakeet, Qwen vLLM, large Transformers). Omnilingual ASR requires Linux/WSL2 with Python 3.11.x.
    • Kroko-ONNX Setup: To use kroko_onnx for recorder-based server use, install with RealtimeSTT[kroko-builder,silero-onnx-cpu] and run stt-install-kroko --build. On Windows, use Python 3.12 x64 and ensure Docker Desktop is running.
    • Storage: Use persistent storage for model caches to avoid redownloading models on restart.
    • Networking: Place the server behind a reverse proxy when exposing it to the internet.
    • Tuning: Adjust --max-sessions, --max-active-speakers, queue depths, and model lanes based on your specific engine and hardware capabilities.
    • Monitoring: Use /health for readiness and /api/metrics for load/latency monitoring.
  9. Optimize realtime transcription performance

    master

    To reduce latency in realtime mode, use a smaller model for realtime transcription than your final model.

    Recommended Configuration:

    • Set enable_realtime_transcription=True.
    • Use a smaller realtime_model_type (e.g., tiny.en).
    • Adjust realtime_processing_pause (e.g., 0.15).

    If you want to save memory, set use_main_model_for_realtime=True. This uses a single shared model, but may reduce responsiveness if the final and realtime tasks contend for the same model resources.

    recorder = AudioToTextRecorder(
        model="small.en",
        enable_realtime_transcription=True,
        realtime_model_type="tiny.en",
        realtime_processing_pause=0.15,
    )
  10. Run Performance and Integration Tests

    master

    The project includes unit tests and opt-in integration tests for measuring ASR performance and latency.

    Unit Tests

    To run fast unit tests (without loading ASR models):

    python -m unittest -v \
      tests.unit.test_fastapi_server_protocol \
      tests.unit.test_fastapi_server_multi_user

    ASR Integration and Performance Tests

    To run tests that load real engines and compare transcripts against expected results, set the following environment variables:

    • REALTIMESTT_RUN_FASTAPI_MULTI_USER_ASR=1: Runs integration tests.
    • REALTIMESTT_RUN_FASTAPI_MULTI_USER_PERF=1: Runs performance tests (measures latency).

    Example command:

    REALTIMESTT_RUN_FASTAPI_MULTI_USER_PERF=1 \
    python -m unittest -v tests.unit.test_fastapi_server_multi_user_asr_integration

    To save the performance report as a JSON file, set REALTIMESTT_FASTAPI_ASR_METRICS_JSON=/path/to/report.json.

  11. Authenticate with Hugging Face for Cohere models

    master
    The Cohere Transcribe adapter loads models locally via Transformers. If the model is gated, you must authenticate using a Hugging Face token. You can do this by running huggingface-cli login or by setting the HF_TOKEN environment variable.