Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix(parakeet): decode long audio in pieces cut at pauses (#624)

Shai Shmuel4d0e3c6a0680
diff --git a/packages/sie_server/src/sie_server/adapters/parakeet/adapter.py b/packages/sie_server/src/sie_server/adapters/parakeet/adapter.py
index 8c58db10c..33ff3796a 100644
--- a/packages/sie_server/src/sie_server/adapters/parakeet/adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/parakeet/adapter.py
@@ -9,20 +9,28 @@ Decoding is the batched greedy TDT loop in :mod:`.decoding` rather than
``generate()``, whose TDT path has no per-frame symbol limit and can repeat a
token until the output buffer is full.
-A request's audio is decoded in one pass, however long. Rows are grouped by
-length so that a forward pass never holds more than ``max_padded_batch_ms`` of
-padded audio: encoder self-attention grows with the square of a row's length,
-so with that budget no batch needs more memory than a single recording of the
-budget's length.
+Audio longer than 30 s is decoded in pieces of at most 30 s, each cut at the
+quietest 100 ms in the last 8 s before its 30 s mark, with no overlap. In one
+long pass the model can skip whole stretches of speech, and NVIDIA's NeMo
+decoder does the same; longer pieces such as 60 s still skip speech. A
+request's text joins its pieces' texts with spaces, and each piece's
+timestamps are shifted to where the piece starts.
+
+The pieces of every request in a batch are decoded as rows, grouped by length
+so that a forward pass never holds more than ``max_padded_batch_ms`` of padded
+audio: encoder self-attention grows with the square of a row's length, so with
+that budget no batch needs more memory than a single recording of the budget's
+length.
The model occasionally returns nothing for a short, tightly cut clip that
-contains speech. Each empty row of at most ``_EMPTY_RETRY_MAX_S`` (30 s) is
-decoded again on its own, first with 0.25 s of silence appended and then, if
-still empty, with 0.25 s on both sides. Padding is never added to the batched
-pass, where it lowers accuracy. A longer empty row is returned as it is: every
-empty row the padding recovered in testing was under 12 s, and a long
-recording that decodes to nothing (silence, music) would otherwise run
-through the encoder three times.
+contains speech. When a request's last piece (the whole request, for audio of
+at most 30 s) decodes to nothing, it is decoded again on its own, first with
+0.25 s of silence appended and then, if still empty, with 0.25 s on both
+sides. Padding is never added to the batched pass, where it lowers accuracy.
+Earlier pieces are not re-decoded: they are 22-30 s long and end at a pause,
+every empty row the padding recovered in testing was under 12 s, and a long
+recording that decodes to nothing (silence, music) would otherwise run through
+the encoder three times.
"""
from __future__ import annotations
@@ -46,7 +54,7 @@ from sie_server.core.prepared import AudioPayload
from sie_server.core.preprocessor.audio import AudioPreprocessor
if TYPE_CHECKING:
- from collections.abc import Sequence
+ from collections.abc import Container, Sequence
from sie_server.types.inputs import Item
@@ -91,10 +99,14 @@ _ERR_ENCODE_NOT_SUPPORTED = "ParakeetTDTAdapter does not support encode(). Use e
_MIN_TRANSFORMERS_VERSION = Version("5.18")
_RUNTIME_OPTIONS = frozenset({"language", "temperature", "timestamp_granularities"})
_TIMESTAMP_GRANULARITIES = frozenset({"segment", "word"})
+# Audio is decoded in pieces of at most _PIECE_MAX_S seconds, each cut in the
+# middle of the quietest _CUT_FRAME_S frame in the last _CUT_SEARCH_S before
+# its _PIECE_MAX_S mark.
+_PIECE_MAX_S = 30.0
+_CUT_SEARCH_S = 8.0
+_CUT_FRAME_S = 0.1
# Seconds of silence (leading, trailing) for the re-decodes of an empty row, in order.
_EMPTY_RETRY_PADDING_S = ((0.0, 0.25), (0.25, 0.25))
-# Longest empty row, in seconds, that is re-decoded with padding.
-_EMPTY_RETRY_MAX_S = 30.0
# A segment ends at a word ending in sentence-final punctuation (. ! ? or an
# ellipsis, optionally followed by closing quotes or brackets), or once it spans
# this many seconds.
@@ -254,18 +266,32 @@ class ParakeetTDTAdapter(BaseAdapter):
raise ValueError(msg)
waveforms = [_waveform(payload) for payload in payloads]
- transcripts = self._transcribe(waveforms)
- data = [
- self._transcript_data(transcript, payload, granularities)
- for transcript, payload in zip(transcripts, payloads, strict=True)
- ]
+ windows = [_pause_windows(waveform, self._sample_rate) for waveform in waveforms]
+ rows: list[np.ndarray] = []
+ last_rows: set[int] = set()
+ for waveform, spans in zip(waveforms, windows, strict=True):
+ if len(spans) > 1:
+ logger.debug(
+ "Decoding %.1f s of audio as %d Parakeet pieces cut at pauses",
+ waveform.shape[0] / self._sample_rate,
+ len(spans),
+ )
+ rows.extend(waveform[start:end] for start, end in spans)
+ last_rows.add(len(rows) - 1)
+ transcripts = self._transcribe(rows, retry_rows=last_rows)
+ data: list[dict[str, Any]] = []
+ first = 0
+ for spans, payload in zip(windows, payloads, strict=True):
+ data.append(self._transcript_data(transcripts[first : first + len(spans)], spans, payload, granularities))
+ first += len(spans)
return ExtractOutput(
entities=[[] for _ in data],
data=data,
batch_size=len(data),
)
- def _transcribe(self, waveforms: list[np.ndarray]) -> list[_Transcript]:
+ def _transcribe(self, waveforms: list[np.ndarray], *, retry_rows: Container[int]) -> list[_Transcript]:
+ """Decode rows in length-grouped passes; an empty row in ``retry_rows`` is re-decoded with padding."""
transcripts = [_Transcript() for _ in waveforms]
# A clip too short to normalize holds no speech; it is returned empty.
decodable = [index for index, waveform in enumerate(waveforms) if waveform.shape[0] >= self._min_samples]
@@ -275,10 +301,9 @@ class ParakeetTDTAdapter(BaseAdapter):
for row, transcript in zip(rows, self._decode([waveforms[row] for row in rows]), strict=True):
transcripts[row] = transcript
- retry_max_samples = round(_EMPTY_RETRY_MAX_S * self._sample_rate)
retried = 0
for row in decodable:
- if transcripts[row].text or waveforms[row].shape[0] > retry_max_samples:
+ if transcripts[row].text or row not in retry_rows:
continue
retried += 1
for leading_s, trailing_s in _EMPTY_RETRY_PADDING_S:
@@ -333,26 +358,40 @@ class ParakeetTDTAdapter(BaseAdapter):
def _transcript_data(
self,
- transcript: _Transcript,
+ pieces: Sequence[_Transcript],
+ spans: Sequence[tuple[int, int]],
payload: AudioPayload,
granularities: frozenset[str],
) -> dict[str, Any]:
+ """One request's response from its pieces' transcripts and sample spans, in order."""
data: dict[str, Any] = {
- "text": transcript.text,
+ "text": " ".join(piece.text for piece in pieces if piece.text),
"language": None,
"duration_ms": payload.duration_ms,
}
if not granularities:
return data
- words = _words_from_tokens(self._timed_tokens(transcript, payload.duration_s))
+ # Each piece's words are merged from its own tokens, so a piece boundary
+ # is always a word boundary.
+ starts_s = [start / self._sample_rate for start, _ in spans]
+ ends_s = [*starts_s[1:], payload.duration_s]
+ words = [
+ word
+ for piece, start_s, end_s in zip(pieces, starts_s, ends_s, strict=True)
+ for word in _words_from_tokens(self._timed_tokens(piece, start_s, end_s))
+ ]
if "word" in granularities:
data["words"] = words
if "segment" in granularities:
data["segments"] = _segments_from_words(words)
return data
- def _timed_tokens(self, transcript: _Transcript, duration_s: float) -> list[dict[str, Any]]:
- """Token start/end seconds from each decode step's frame and duration."""
+ def _timed_tokens(self, transcript: _Transcript, start_s: float, end_s: float) -> list[dict[str, Any]]:
+ """Token start/end seconds from each decode step's frame and duration.
+
+ Times are shifted by ``start_s``, where the decoded row begins in its
+ request, and kept within ``[start_s, end_s]``.
+ """
hypothesis = transcript.hypothesis
if not transcript.text or not hypothesis.step_ids:
return []
@@ -365,8 +404,8 @@ class ParakeetTDTAdapter(BaseAdapter):
)
tokens = []
for offset in offsets[0]:
- start = min(max(float(offset["start"]) - transcript.offset_s, 0.0), duration_s)
- end = min(max(float(offset["end"]) - transcript.offset_s, start), duration_s)
+ start = min(max(float(offset["start"]) - transcript.offset_s + start_s, start_s), end_s)
+ end = min(max(float(offset["end"]) - transcript.offset_s + start_s, start), end_s)
tokens.append({"token": str(offset["token"]), "start": start, "end": end})
return tokens
@@ -436,6 +475,39 @@ def _pad(waveform: np.ndarray, sample_rate: int, leading_s: float, trailing_s: f
return np.concatenate([leading, waveform, trailing])
+def _pause_windows(waveform: np.ndarray, sample_rate: int) -> list[tuple[int, int]]:
+ """Split a recording into contiguous, non-overlapping ``(start, end)`` sample spans.
+
+ While more than ``_PIECE_MAX_S`` remains, the next span ends in the middle
+ of the quietest ``_CUT_FRAME_S`` frame (by RMS, the first on ties) among the
+ frames in the last ``_CUT_SEARCH_S`` before the ``_PIECE_MAX_S`` mark. A
+ recording of at most ``_PIECE_MAX_S`` is one span.
+ """
+ total = waveform.shape[0]
+ piece = round(_PIECE_MAX_S * sample_rate)
+ if total <= piece:
+ return [(0, total)]
+ hop = round(_CUT_FRAME_S * sample_rate)
+ search = round(_CUT_SEARCH_S * sample_rate)
+ frames = total // hop
+ # RMS is taken at int16 scale, which is exact for a waveform of int16 / 32768.
+ # There the 1e-9 floor is far below one int16 step squared; on the [-1, 1)
+ # scale it is about one step squared and rounds near-equal quiet frames
+ # into ties.
+ scaled = waveform[: frames * hop].reshape(frames, hop) * np.float32(32_768.0)
+ rms = np.sqrt(np.mean(np.square(scaled), axis=1) + 1e-9)
+ windows: list[tuple[int, int]] = []
+ start = 0
+ while total - start > piece:
+ low = (start + piece - search) // hop
+ high = (start + piece) // hop
+ cut = (low + int(np.argmin(rms[low:high]))) * hop + hop // 2
+ windows.append((start, cut))
+ start = cut
+ windows.append((start, total))
+ return windows
+
+
def _length_chunks(lengths: Sequence[int], max_padded: int) -> list[list[int]]:
"""Group indices, longest first, so ``rows * longest row`` stays within ``max_padded``.
diff --git a/packages/sie_server/tests/adapters/test_parakeet.py b/packages/sie_server/tests/adapters/test_parakeet.py
index ed79a6d7e..208562e71 100644
--- a/packages/sie_server/tests/adapters/test_parakeet.py
+++ b/packages/sie_server/tests/adapters/test_parakeet.py
@@ -1,8 +1,10 @@
from __future__ import annotations
import dataclasses
+import logging
import re
import sys
+from itertools import pairwise
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -16,12 +18,13 @@ from packaging.specifiers import SpecifierSet
from sie_sdk.bundle_utils import match_bundle_models
from sie_server.adapters.parakeet import adapter as parakeet_adapter
from sie_server.adapters.parakeet.adapter import (
- _EMPTY_RETRY_MAX_S,
SUPPORTED_LANGUAGES,
ParakeetTDTAdapter,
_length_chunks,
+ _pause_windows,
_segments_from_words,
_Transcript,
+ _waveform,
_words_from_tokens,
)
from sie_server.adapters.parakeet.decoding import TdtHypothesis, greedy_tdt_decode
@@ -38,6 +41,10 @@ MODEL_ID = "nvidia/parakeet-tdt-0.6b-v3"
BLANK = 9
VOCAB = 10
DURATIONS = (0, 1, 2, 3, 4)
+SAMPLE_RATE = 16_000
+# 100 ms cut-search frame and 30 s longest piece, in samples.
+FRAME = 1_600
+PIECE = 30 * SAMPLE_RATE
# ---------------------------------------------------------------------------
@@ -239,6 +246,13 @@ def _payload(*, duration_ms: int = 1_000) -> AudioPayload:
)
+def _samples_payload(samples: np.ndarray) -> AudioPayload:
+ return dataclasses.replace(
+ _payload(duration_ms=samples.shape[0] // 16),
+ pcm_s16le=samples.astype("<i2").tobytes(),
+ )
+
+
def _prepared(*payloads: AudioPayload) -> list[PreparedItem[AudioPayload]]:
return [
PreparedItem(payload=payload, cost=payload.duration_ms, original_index=index)
@@ -384,7 +398,7 @@ def test_transcribe_groups_rows_by_padded_length_budget() -> None:
adapter._decode = fake_decode
lengths = [4_800, 9_600, 24_000, 3_200, 8_000] # 0.3, 0.6, 1.5, 0.2, 0.5 s
- transcripts = adapter._transcribe([np.ones(length, dtype=np.float32) for length in lengths])
+ transcripts = adapter._transcribe([np.ones(length, dtype=np.float32) for length in lengths], retry_rows=())
# Longest first; a chunk holds rows * longest <= 1 s; an over-budget row runs alone.
assert calls == [[24_000], [9_600], [8_000, 4_800], [3_200]]
@@ -419,7 +433,7 @@ def test_empty_rows_are_redecoded_alone_with_end_then_both_sides_padding() -> No
return results
adapter._decode = fake_decode
- transcripts = adapter._transcribe(originals)
+ transcripts = adapter._transcribe(originals, retry_rows=range(len(originals)))
assert calls == [
([16_000, 8_000, 6_400, 4_800], 0.0), # one batched pass; the 100-sample clip is too short to decode
@@ -433,7 +447,7 @@ def test_empty_rows_are_redecoded_alone_with_end_then_both_sides_padding() -> No
assert [transcript.offset_s for transcript in transcripts] == [0.0, 0.0, 0.25, 0.0, 0.0]
-def test_empty_rows_longer_than_thirty_seconds_are_not_redecoded() -> None:
+def test_only_empty_rows_listed_for_retry_are_redecoded() -> None:
adapter = _loaded_adapter()
calls: list[list[int]] = []
@@ -442,13 +456,14 @@ def test_empty_rows_longer_than_thirty_seconds_are_not_redecoded() -> None:
return [_transcript("", offset_s) for _ in waveforms]
adapter._decode = fake_decode
- limit = round(_EMPTY_RETRY_MAX_S * 16_000)
- transcripts = adapter._transcribe([np.ones(limit + 1, dtype=np.float32), np.ones(limit, dtype=np.float32)])
+ transcripts = adapter._transcribe(
+ [np.ones(PIECE + 1, dtype=np.float32), np.ones(PIECE, dtype=np.float32), np.ones(8_000, dtype=np.float32)],
+ retry_rows={1},
+ )
- assert _EMPTY_RETRY_MAX_S == 30.0
- # The row just over 30 s gets only the batched pass; the 30 s row is retried twice.
- assert calls == [[limit + 1, limit], [limit + 4_000], [limit + 8_000]]
- assert [transcript.text for transcript in transcripts] == ["", ""]
+ # Every row gets the batched pass; only row 1 is retried, twice.
+ assert calls == [[PIECE + 1, PIECE, 8_000], [PIECE + 4_000], [PIECE + 8_000]]
+ assert [transcript.text for transcript in transcripts] == ["", "", ""]
def test_decode_runs_encoder_then_greedy_loop_and_processor_text(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -626,6 +641,296 @@ def test_segments_split_at_sentence_ends_and_after_thirty_seconds() -> None:
assert _segments_from_words([]) == []
+# ---------------------------------------------------------------------------
+# Long audio: pieces cut at pauses
+# ---------------------------------------------------------------------------
+
+
+def _with_frames(seconds: float, level: float, frames: dict[int, float]) -> np.ndarray:
+ """``seconds`` of constant ``level`` with each listed 100 ms frame set to its own level."""
+ waveform = np.full(round(seconds * SAMPLE_RATE), level, dtype=np.float32)
+ for frame, frame_level in frames.items():
+ waveform[frame * FRAME : (frame + 1) * FRAME] = frame_level
+ return waveform
+
+
+def _cut(frame: int) -> int:
+ return frame * FRAME + FRAME // 2
+
+
[email protected]("length", [0, 1, SAMPLE_RATE, PIECE - 1, PIECE])
+def test_pause_windows_keep_audio_of_at_most_thirty_seconds_whole(length: int) -> None:
+ waveform = np.ones(length, dtype=np.float32)
+ waveform[25 * SAMPLE_RATE : 26 * SAMPLE_RATE] = 0.0
+
+ assert _pause_windows(waveform, SAMPLE_RATE) == [(0, length)]
+
+
+def test_pause_windows_split_audio_one_sample_over_thirty_seconds() -> None:
+ waveform = np.ones(PIECE + 1, dtype=np.float32)
+ waveform[250 * FRAME : 251 * FRAME] = 0.0
+
+ assert _pause_windows(waveform, SAMPLE_RATE) == [(0, _cut(250)), (_cut(250), PIECE + 1)]
+
+
[email protected]("quiet_frame", [220, 263, 299])
+def test_pause_windows_cut_at_the_quietest_frame_in_the_last_eight_seconds(quiet_frame: int) -> None:
+ # Frames 220-299 (22.0-30.0 s) are searched; the silent frames just outside
+ # them are not. The quietest frame holds one click (RMS 0.0125); frame 240,
+ # a steady hum (RMS 0.05), has the lower peak but is louder by RMS.
+ waveform = _with_frames(40, 1.0, {219: 0.0, 300: 0.0, quiet_frame: 0.0, 240: 0.05})
+ waveform[quiet_frame * FRAME + 10] = 0.5
+
+ assert _pause_windows(waveform, SAMPLE_RATE) == [(0, _cut(quiet_frame)), (_cut(quiet_frame), waveform.shape[0])]
+
+
+def test_pause_windows_take_the_first_of_equally_quiet_frames() -> None:
+ waveform = _with_frames(40, 1.0, {230: 0.0, 270: 0.0})
+
+ assert _pause_windows(waveform, SAMPLE_RATE)[0] == (0, _cut(230))
+
+
[email protected]("quiet_frame", [470, 549])
+def test_pause_windows_search_from_each_cut(quiet_frame: int) -> None:
+ # After the cut at 25.05 s the next search is frames 470-549 (47.0-55.0 s),
+ # whose middles 47.05-54.95 s fall in the last 8 s before 55.05 s, 30 s from
+ # that cut. The silent frames just outside them are not searched; frame 550
+ # would be if the search were the last 8 s before the 60 s mark.
+ waveform = _with_frames(70, 1.0, {250: 0.0, 469: 0.0, quiet_frame: 0.1, 550: 0.0})
+
+ assert _pause_windows(waveform, SAMPLE_RATE) == [
+ (0, _cut(250)),
+ (_cut(250), _cut(quiet_frame)),
+ (_cut(quiet_frame), 70 * SAMPLE_RATE),
+ ]
+
+
[email protected](("extra", "cuts"), [(0, [_cut(250)]), (1, [_cut(250), _cut(520)])])
+def test_pause_windows_cut_again_only_if_more_than_thirty_seconds_remain(extra: int, cuts: list[int]) -> None:
+ # With exactly 30 s after the cut at 25.05 s, that is the last piece; with
+ # one more sample, silent frame 520 is cut too.
+ waveform = np.ones(_cut(250) + PIECE + extra, dtype=np.float32)
+ for frame in (250, 520):
+ waveform[frame * FRAME : (frame + 1) * FRAME] = 0.0
+
+ assert _pause_windows(waveform, SAMPLE_RATE) == list(pairwise([0, *cuts, waveform.shape[0]]))
+
+
+def test_pause_windows_rank_frames_by_rms_at_int16_scale() -> None:
+ # Frame 260 is quieter than frame 230 by one unit of int16 sum of squares
+ # (6,551,882 against 6,551,883). With the RMS floor added on the [-1, 1)
+ # scale the two would tie and the cut would fall in frame 230.
+ samples = np.full(31 * SAMPLE_RATE, 3_000, dtype="<i2")
+ for frame, head in ((230, [63] * 4 + [65] * 3 + [50]), (260, [63] * 2 + [65] * 4 + [46])):
+ samples[frame * FRAME : (frame + 1) * FRAME] = 64
+ samples[frame * FRAME : frame * FRAME + len(head)] = head
+ sums = [int(np.sum(np.square(samples[f * FRAME : (f + 1) * FRAME].astype(np.int64)))) for f in (230, 260)]
+ assert sums == [6_551_883, 6_551_882]
+
+ waveform = _waveform(_samples_payload(samples))
+
+ assert _pause_windows(waveform, SAMPLE_RATE) == [(0, _cut(260)), (_cut(260), samples.shape[0])]
+
+
[email protected]("seconds", [30.001, 61.0, 95.55, 720.0])
+def test_pause_windows_cover_the_recording_with_contiguous_pieces_of_at_most_thirty_seconds(seconds: float) -> None:
+ rng = np.random.default_rng(7)
+ length = round(seconds * SAMPLE_RATE)
+ loudness = np.repeat(rng.random(length // FRAME + 1), FRAME)[:length]
+ waveform = (rng.normal(0.0, 0.1, length) * loudness).astype(np.float32)
+
+ windows = _pause_windows(waveform, SAMPLE_RATE)
+
+ assert len(windows) > 1
+ assert windows[0][0] == 0
+ assert windows[-1][1] == length
+ assert all(end == next_start for (_, end), (next_start, _) in pairwise(windows))
+ assert all(0 < end - start <= PIECE for start, end in windows)
+ # Every cut falls in the last 8 s before its piece's 30 s mark.
+ assert all(start + PIECE - 8 * SAMPLE_RATE <= end < start + PIECE for start, end in windows[:-1])
+
+
+def _recording_decoder(texts: dict[tuple[int, float], _Transcript]) -> tuple[Any, list[tuple[list[int], float]]]:
+ """A ``_decode`` stand-in returning ``texts[(row length, offset_s)]`` or an empty transcript."""
+ calls: list[tuple[list[int], float]] = []
+
+ def fake_decode(waveforms: list[np.ndarray], *, offset_s: float = 0.0) -> list[_Transcript]:
+ calls.append(([waveform.shape[0] for waveform in waveforms], offset_s))
+ return [
+ dataclasses.replace(texts.get((waveform.shape[0], offset_s), _Transcript()), offset_s=offset_s)
+ for waveform in waveforms
+ ]
+
+ return fake_decode, calls
+
+
+def _hypothesis(step_id: int) -> TdtHypothesis:
+ return TdtHypothesis(token_ids=[step_id], step_ids=[step_id], step_durations=[1])
+
+
+def test_requests_of_at_most_thirty_seconds_are_decoded_whole() -> None:
+ adapter = _loaded_adapter()
+ # Exactly 30 s, with a pause where longer audio would be cut.
+ samples = np.full(PIECE, 1_000, dtype="<i2")
+ samples[250 * FRAME : 251 * FRAME] = 0
+ adapter._decode, calls = _recording_decoder({(PIECE, 0.0): _Transcript(text="Whole.", hypothesis=_hypothesis(1))})
+ adapter._processor.decode.return_value = (["Whole."], [[_timed("Whole", 29.5, 29.9), _timed(".", 29.9, 30.4)]])
+
+ output = adapter.extract(
+ [Item()],
+ options={"timestamp_granularities": ["word"]},
+ prepared_items=_prepared(_samples_payload(samples)),
+ )
+
+ assert calls == [([PIECE], 0.0)]
+ assert output.data == [
+ {
+ "text": "Whole.",
+ "language": None,
+ "duration_ms": 30_000,
+ "words": [{"word": "Whole.", "start": 29.5, "end": 30.0}],
+ }
+ ]
+
+
+def _long_samples(levels: tuple[int, int, int] = (1_000, 2_000, 3_000)) -> np.ndarray:
+ """70 s whose silent frames cut it into 25.05, 27.0 and 17.95 s pieces of the given levels."""
+ samples = np.empty(70 * SAMPLE_RATE, dtype="<i2")
+ for (start, end), level in zip(pairwise([0, _cut(250), _cut(520), samples.shape[0]]), levels, strict=True):
+ samples[start:end] = level
+ for frame in (250, 520):
+ samples[frame * FRAME : (frame + 1) * FRAME] = 0
+ return samples
+
+
+def test_long_request_is_decoded_as_pieces_and_joins_their_texts(caplog: pytest.LogCaptureFixture) -> None:
+ adapter = _loaded_adapter()
+ first, middle, last = _cut(250), _cut(520) - _cut(250), 70 * SAMPLE_RATE - _cut(520)
+ adapter._decode, calls = _recording_decoder(
+ {
+ (first, 0.0): _Transcript(text="First piece."),
+ (last, 0.0): _Transcript(text="Last piece."),
+ (SAMPLE_RATE, 0.0): _Transcript(text="Short."),
+ }
+ )
+
+ with caplog.at_level(logging.DEBUG, logger=parakeet_adapter.__name__):
+ output = adapter.extract(
+ [Item(), Item()],
+ prepared_items=_prepared(_samples_payload(_long_samples()), _payload(duration_ms=1_000)),
+ )
+
+ assert (first, middle, last) == (400_800, 432_000, 287_200)
+ # Every piece of every request is a row of the same length-grouped pass. The
+ # empty middle piece is not re-decoded with padding: only a request's last
+ # piece is.
+ assert calls == [([middle, first, last, SAMPLE_RATE], 0.0)]
+ assert output.batch_size == 2
+ assert output.data == [
+ {"text": "First piece. Last piece.", "language": None, "duration_ms": 70_000},
+ {"text": "Short.", "language": None, "duration_ms": 1_000},
+ ]
+ assert "Decoding 70.0 s of audio as 3 Parakeet pieces cut at pauses" in caplog.text
+
+
+def test_long_request_timestamps_are_shifted_to_each_piece_and_never_span_two() -> None:
+ adapter = _loaded_adapter()
+ first, middle, last = _cut(250), _cut(520) - _cut(250), 70 * SAMPLE_RATE - _cut(520)
+ adapter._decode, calls = _recording_decoder(
+ {
+ (first, 0.0): _Transcript(text="Good morning,", hypothesis=_hypothesis(1)),
+ (middle, 0.0): _Transcript(text="everyone. So", hypothesis=_hypothesis(2)),
+ # The last piece decodes empty, then recovers with 0.25 s on both sides.
+ (last + 8_000, 0.25): _Transcript(text="far so good. Bye", hypothesis=_hypothesis(3)),
+ }
+ )
+ # Token times relative to each decoded row; the first token of a piece has no leading space.
+ row_tokens = {
+ 1: [_timed("Good", 23.0, 23.4), _timed(" morning", 24.4, 25.3), _timed(",", 25.3, 25.4)],
+ 2: [_timed("every", 0.0, 0.4), _timed("one", 0.4, 0.56), _timed(".", 0.56, 0.56), _timed(" So", 25.75, 26.25)],
+ 3: [
+ _timed("far", 0.1, 0.55),
+ _timed(" so", 0.65, 0.85),
+ _timed(" good", 0.95, 1.25),
+ _timed(".", 1.25, 1.25),
+ _timed(" Bye", 18.15, 18.4),
+ ],
+ }
+ adapter._processor.decode.side_effect = lambda ids, **_: (["text"], [row_tokens[int(ids[0, 0])]])
+
+ output = adapter.extract(
+ [Item()],
+ options={"timestamp_granularities": ["word", "segment"]},
+ prepared_items=_prepared(_samples_payload(_long_samples())),
+ )
+
+ assert calls == [([middle, first, last], 0.0), ([last + 4_000], 0.0), ([last + 8_000], 0.25)]
+ (data,) = output.data or []
+ assert data["text"] == "Good morning, everyone. So far so good. Bye"
+ assert data["duration_ms"] == 70_000
+ # Pieces span 0-25.05, 25.05-52.05 and 52.05-70.0 s. Each token is shifted by
+ # its piece's start (less the retry's 0.25 s leading pad, in the last piece)
+ # and kept within the piece, so "morning," ends at the first cut and "far"
+ # starts at the second.
+ words = data["words"]
+ assert words == [
+ {"word": "Good", "start": 23.0, "end": 23.4},
+ {"word": "morning,", "start": 24.4, "end": 25.05},
+ {"word": "everyone.", "start": 25.05, "end": 25.61},
+ {"word": "So", "start": 50.8, "end": 51.3},
+ {"word": "far", "start": 52.05, "end": 52.35},
+ {"word": "so", "start": 52.45, "end": 52.65},
+ {"word": "good.", "start": 52.75, "end": 53.05},
+ {"word": "Bye", "start": 69.95, "end": 70.0},
+ ]
+ assert all(word["start"] <= word["end"] for word in words)
+ assert all(word["end"] <= after["start"] for word, after in pairwise(words))
+ # A sentence that crosses a cut makes one segment.
+ assert data["segments"] == [
+ {"id": 0, "start": 23.0, "end": 25.61, "text": "Good morning, everyone."},
+ {"id": 1, "start": 50.8, "end": 53.05, "text": "So far so good."},
+ {"id": 2, "start": 69.95, "end": 70.0, "text": "Bye"},
+ ]
+
+
+def test_long_silent_request_re_decodes_only_its_last_piece() -> None:
+ adapter = _loaded_adapter()
+ adapter._decode, calls = _recording_decoder({})
+
+ output = adapter.extract([Item()], prepared_items=_prepared(_payload(duration_ms=70_000)))
+
+ # Silence ties every frame, so each cut is at the first frame searched:
+ # pieces of 22.05, 22.0 and 25.95 s. Only the last is re-decoded.
+ assert calls == [([415_200, 352_800, 352_000], 0.0), ([419_200], 0.0), ([423_200], 0.25)]
+ assert output.data == [{"text": "", "language": None, "duration_ms": 70_000}]
+
+
+def _levels_decode(waveforms: list[np.ndarray], *, offset_s: float = 0.0) -> list[_Transcript]:
+ """A ``_decode`` stand-in whose text for a row lists the non-zero int16 levels in it."""
+ return [
+ _Transcript(text="+".join(str(level) for level in np.unique(np.rint(row * 32_768).astype(int)) if level))
+ for row in waveforms
+ ]
+
+
+def test_each_request_gets_the_texts_of_its_own_pieces_in_order() -> None:
+ adapter = _loaded_adapter()
+ adapter._decode = _levels_decode
+
+ output = adapter.extract(
+ [Item(), Item(), Item()],
+ prepared_items=_prepared(
+ _samples_payload(_long_samples((1_000, 2_000, 3_000))),
+ _samples_payload(_long_samples((4_000, 5_000, 6_000))),
+ _samples_payload(np.full(SAMPLE_RATE, 7_000, dtype="<i2")),
+ ),
+ )
+
+ # Each row is the recording between its cuts, and each request takes its
+ # own rows from the shared pass.
+ assert [data["text"] for data in output.data or []] == ["1000 2000 3000", "4000 5000 6000", "7000"]
+
+
def _fake_transformers(
monkeypatch: pytest.MonkeyPatch, *, decoder_type: str | None = None, version: str = "5.18.0"
) -> tuple[MagicMock, MagicMock, MagicMock]: