omi icon indicating copy to clipboard operation
omi copied to clipboard

Python SDK: configurable batch duration for local Whisper transcription

Open mimienco opened this issue 2 months ago • 2 comments

The Python SDK's local Whisper adapter currently waits for a fixed five seconds of mono 16 kHz PCM before invoking its model or injected runner (sdks/python/omi/stt/whisper.py, Git blob deceb9ea2c5c2c3ae1fc7798a0d20b1e0aba880a; inspected main 9ff63a63b047ec756b6a4e3d726bac5bf5d6440e). An application using a fast local runner cannot select a shorter audio batch through create_transcriber() or transcribe(). This is an enhancement proposal, not a claim that the existing documented/default behavior is a bug. I searched existing Whisper batching/duration issues and found no equivalent SDK proposal; language selection in #13071 and session lifecycle in #13011 are separate scopes.

Would an optional batch_seconds=5.0 be useful? A small candidate preserves the current default, accepts 0.1–30 seconds, rejects invalid/non-finite values before loading a model, quantizes the threshold to complete PCM samples, and retains the complete queue chunk that crosses the threshold. It does not introduce time-based flushing, resampling, a provider change, or a change to the injected runner's bytes-only contract. Shorter batches trade acoustic context for earlier invocation; this does not promise recognition accuracy or a wall-clock response deadline.

Evidence: I prepared and ran ten focused offline unittest tests on Python 3.13.5 through the real transcribe() wrapper, factory, audio queue, threaded runner dispatch, and transcript callback. All ten pass with the candidate, covering omitted/explicit five-second defaults, one-second and fractional thresholds, complete-sample rounding, minimum/maximum settings, repeated batches, oversized input preservation, eight invalid values, and runner error propagation. The original source retains its two control passes but rejects the new keyword in the feature cases. Source snapshots were checked against their upstream Git blob hashes. No live service, model download/inference, device, account, or real credentials were used. These are focused configuration/PCM-plumbing tests, not a full SDK-suite, repository-preflight, hosted-CI, or speech-quality result. Documentation integration and those PR gates remain before any ready-to-merge contribution.

@josancamon19 — following the contribution guide's invitation to suggest paid work, would you sponsor this bounded enhancement, tests and SDK documentation for US$10 via the documented private PayPal process after acceptance and merge? The amount is requested, not approved, reserved, earned, or paid. Please decline or redirect the scope if it is not useful. This candidate was prepared by an OpenAI coding assistant for @mimienco with the account owner's authorization. Payment details are deliberately omitted.

Candidate implementation (not a submitted PR or accepted specification)
--- a/sdks/python/omi/stt/whisper.py
+++ b/sdks/python/omi/stt/whisper.py
@@ -11,7 +11,24 @@
     Feature gate: only importable/usable when a runner is provided or whisper is installed.
     """
 
-    def __init__(self, *, model_name: str = "tiny.en", runner: Optional[Callable[[bytes], str]] = None) -> None:
+    def __init__(
+        self,
+        *,
+        model_name: str = "tiny.en",
+        runner: Optional[Callable[[bytes], str]] = None,
+        batch_seconds: float = 5.0,
+    ) -> None:
+        """Batch 0.1-30 seconds of 16 kHz mono s16le PCM before inference.
+
+        This is an audio-duration threshold, not a wall-clock deadline. The
+        complete queue chunk that reaches the threshold is retained, just as
+        with the default five-second batching behavior.
+        """
+        if not 0.1 <= batch_seconds <= 30.0:
+            raise ValueError("batch_seconds must be between 0.1 and 30 seconds")
+        # Quantize to complete PCM samples, never an odd number of bytes.
+        self._target_bytes = int(16000 * batch_seconds) * 2
         self.model_name = model_name
         self.runner = runner
         self._model = None
@@ -32,7 +49,7 @@
     ) -> None:
         # Batch PCM for a simple offline-style loop (parity surface, not ultra-low-latency).
         buffer = bytearray()
-        target = 16000 * 2 * 5  # ~5s mono s16le
+        target = self._target_bytes
         while True:
             chunk = await audio_queue.get()
             buffer.extend(chunk)
Small runnable public-wrapper verification

Run with PYTHONPATH=sdks/python python verify_batching.py from a checkout after applying the candidate. The script uses only standard-library dependencies and an injected runner; the original adapter raises TypeError for the new option.

import asyncio
import contextlib
from omi.transcribe import transcribe


async def verify():
    queue = asyncio.Queue()
    queue.put_nowait(b"\x01\x00" * 16000)  # one second of synthetic PCM
    transcript = asyncio.get_running_loop().create_future()
    batches = []

    def runner(pcm):
        batches.append(pcm)
        return "synthetic transcript"

    task = asyncio.create_task(transcribe(
        queue, "", transcript.set_result,
        engine="whisper", runner=runner, batch_seconds=1.0,
    ))
    try:
        done, _ = await asyncio.wait(
            (task, transcript), timeout=3,
            return_when=asyncio.FIRST_COMPLETED,
        )
        if task in done:
            await task
        assert transcript in done, "No transcript callback"
        assert transcript.result() == "synthetic transcript"
        assert batches == [b"\x01\x00" * 16000]
        print("PASS: one-second PCM batch through public SDK wrapper")
    finally:
        task.cancel()
        with contextlib.suppress(asyncio.CancelledError):
            await task


asyncio.run(verify())

mimienco avatar Sep 08 '26 16:09 mimienco

I have implemented this enhancement and added comprehensive unit tests in PR #13316.

/claim #13155

CreamPle avatar Sep 09 '26 13:09 CreamPle

Thanks for putting this together. We aren't doing bounties at the moment, so we're closing the bounty proposal issues for now — thanks for the fix! 🙏

aryanorastar avatar Nov 05 '26 16:11 aryanorastar