Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions livekit-agents/livekit/agents/inference/stt.py
Original file line number Diff line number Diff line change
Expand Up @@ -1485,7 +1485,8 @@ def _process_transcript(self, data: dict, is_final: bool) -> None:

if not text and not is_final:
return
self._process_start_of_speech()
if text:
self._process_start_of_speech()

speech_data = self._build_speech_data(data)

Expand All @@ -1502,6 +1503,11 @@ def _process_transcript(self, data: dict, is_final: bool) -> None:
)
self._speech_duration = 0

# An empty flush result can account for trailing silence without
# starting another turn after the previous final already ended it.
if not text and not self._speaking:
return

event = stt.SpeechEvent(
type=stt.SpeechEventType.FINAL_TRANSCRIPT,
request_id=request_id,
Expand All @@ -1511,7 +1517,17 @@ def _process_transcript(self, data: dict, is_final: bool) -> None:

if self._speaking:
self._speaking = False
end_event = stt.SpeechEvent(type=stt.SpeechEventType.END_OF_SPEECH)
end_alternatives = []
# speech_data.end_time uses start + duration. Some providers report
# billed audio duration (e.g. Ink-2), so use word timing for EOS.
if (words := data.get("words")) and (last_word_end := words[-1].get("end", 0)) > 0:
end_alternatives = [
replace(speech_data, end_time=self.start_time_offset + last_word_end)
]
end_event = stt.SpeechEvent(
type=stt.SpeechEventType.END_OF_SPEECH,
alternatives=end_alternatives,
)
self._event_ch.send_nowait(end_event)
self._on_end_of_speech()
else:
Expand Down
16 changes: 12 additions & 4 deletions livekit-agents/livekit/agents/stt/fallback_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,8 +368,17 @@ async def _run(self) -> None:
logger.error("all STTs are unavailable, retrying..")

main_stream: RecognizeStream | None = None
# the leg that continues this stream's timeline; a leg created before the timeline
# has a start is seeded when its first frame is forwarded
seeded_stream: RecognizeStream | None = None
forward_input_task: asyncio.Task[None] | None = None

def _seed(stream: RecognizeStream) -> None:
nonlocal seeded_stream
if (origin := self._input_ch.input_started_at) is not None:
stream.start_time_offset = time.time() - origin
seeded_stream = stream

async def _forward_input_task() -> None:
async for data in self._input_ch:
for stream in list(self._recovering_streams):
Expand All @@ -384,6 +393,8 @@ async def _forward_input_task() -> None:
if main_stream is not None:
try:
if isinstance(data, rtc.AudioFrame):
if main_stream is not seeded_stream:
_seed(main_stream)
main_stream.push_frame(data)
elif isinstance(data, self._FlushSentinel):
main_stream.flush()
Expand All @@ -410,10 +421,7 @@ async def _forward_input_task() -> None:
),
)
main_stream._on_provider_progress = self._mark_provider_progress
# update main_stream start time offset so transcript timestamps are properly adjusted
main_stream.start_time_offset = self.start_time_offset + (
time.time() - self._start_time
)
_seed(main_stream)

if forward_input_task is None or forward_input_task.done():
forward_input_task = asyncio.create_task(_forward_input_task())
Expand Down
57 changes: 55 additions & 2 deletions livekit-agents/livekit/agents/stt/multi_speaker_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import asyncio
import contextlib
from collections.abc import AsyncIterable
from dataclasses import dataclass
from dataclasses import dataclass, replace
from typing import TYPE_CHECKING, Any

import numpy as np
Expand All @@ -13,7 +13,13 @@
from .. import utils
from ..language import LanguageCode
from ..log import logger
from ..types import DEFAULT_API_CONNECT_OPTIONS, NOT_GIVEN, APIConnectOptions, NotGivenOr
from ..types import (
DEFAULT_API_CONNECT_OPTIONS,
NOT_GIVEN,
APIConnectOptions,
NotGivenOr,
TimedString,
)
from ..utils.audio import AudioByteStream
from .stt import STT, RecognizeStream, SpeechData, SpeechEvent, SpeechEventType

Expand Down Expand Up @@ -160,6 +166,46 @@ async def _forward_output(stream: RecognizeStream) -> None:
async for ev in stream:
updated_ev = self._detector.on_stt_event(ev)
if updated_ev is not None:
origin = self._input_ch.input_started_at
inner_origin = stream._input_ch.input_started_at
if origin is not None and inner_origin is not None and inner_origin != origin:
# RMS lookup uses audio-relative times. Translate only the output,
# copying data that the provider may share between FINAL and EOS.
offset = inner_origin - origin
updated_ev = replace(
updated_ev,
alternatives=[
replace(
alt,
start_time=alt.start_time + offset
if alt.start_time != 0 or alt.end_time > 0
else alt.start_time,
end_time=alt.end_time + offset
if alt.end_time > 0
else alt.end_time,
words=[
TimedString(
word,
start_time=word.start_time + offset
if utils.is_given(word.start_time)
else NOT_GIVEN,
end_time=word.end_time + offset
if utils.is_given(word.end_time)
else NOT_GIVEN,
start_time_offset=word.start_time_offset + offset
if utils.is_given(word.start_time_offset)
else NOT_GIVEN,
confidence=word.confidence,
speaker_id=word.speaker_id,
)
for word in alt.words
]
if alt.words is not None
else None,
)
for alt in updated_ev.alternatives
],
)
self._event_ch.send_nowait(updated_ev)
elif ev.type == SpeechEventType.FINAL_TRANSCRIPT:
# send an empty final transcript to clear the interim results
Expand Down Expand Up @@ -282,6 +328,13 @@ def push_audio(self, frame: rtc.AudioFrame) -> None:
self._rms_buffer = self._rms_buffer[-self._max_rms_size :]

def on_stt_event(self, ev: SpeechEvent) -> SpeechEvent | None:
if ev.type not in (
SpeechEventType.INTERIM_TRANSCRIPT,
SpeechEventType.PREFLIGHT_TRANSCRIPT,
SpeechEventType.FINAL_TRANSCRIPT,
):
return ev

if not ev.alternatives:
return ev

Expand Down
85 changes: 76 additions & 9 deletions livekit-agents/livekit/agents/stt/stt.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import asyncio
import time
from abc import ABC, abstractmethod
from collections import deque
from collections.abc import AsyncIterable, AsyncIterator, Callable, Sequence
from dataclasses import dataclass, field
from enum import Enum, unique
Expand Down Expand Up @@ -370,6 +371,69 @@ class RecognizeStream(ABC):
class _FlushSentinel:
"""Sentinel to mark when it was flushed"""

class _InputChan(aio.Chan[rtc.AudioFrame | _FlushSentinel]):
"""Input queue that places the provider's timestamps on the caller's timeline.

The provider counts audio from the first frame each connection reads, so the offset
is anchored on the capture time of that frame when it is read.
"""

def __init__(self) -> None:
super().__init__()
# session start wall clock time; the first audio when unset
self.input_started_at: float | None = None
# session start -> capture of the current connection's first frame, or the value
# set before that frame is read (last write wins)
# word end time (connection relative) + offset = word end time (session relative)
self._start_time_offset = 0.0
# capture time of the first frame read since the provider's clock restarted
self._first_frame_at: float | None = None
# push time of each queued frame, in queue order
self._pushed_at: deque[float] = deque()
self._queued_duration = 0.0
self._last_pushed_at = 0.0

@property
def start_time_offset(self) -> float:
return self._start_time_offset

@start_time_offset.setter
def start_time_offset(self, value: float) -> None:
self.input_started_at = time.time() - value
self._start_time_offset = (
value
if self._first_frame_at is None
else self._first_frame_at - self.input_started_at
)

def restart_provider_clock(self) -> None:
"""Anchor the offset again on the next frame read, for a new connection."""
self._first_frame_at = None

def send_nowait(self, value: rtc.AudioFrame | RecognizeStream._FlushSentinel) -> None:
super().send_nowait(value)
if isinstance(value, rtc.AudioFrame):
self._last_pushed_at = time.time()
self._pushed_at.append(self._last_pushed_at)
self._queued_duration += value.duration

def recv_nowait(self) -> rtc.AudioFrame | RecognizeStream._FlushSentinel:
value = super().recv_nowait()
if isinstance(value, rtc.AudioFrame):
pushed_at = self._pushed_at.popleft()
if self._first_frame_at is None:
# a frame is pushed after it is captured, so its capture start is at most
# its own push minus its duration (exact across pauses in the input) and
# at most the last push minus all queued audio (exact for a burst)
self._first_frame_at = min(
pushed_at - value.duration, self._last_pushed_at - self._queued_duration
)
if self.input_started_at is None:
self.input_started_at = self._first_frame_at
self._start_time_offset = self._first_frame_at - self.input_started_at
self._queued_duration -= value.duration
return value

def __init__(
self,
*,
Expand All @@ -387,7 +451,7 @@ def __init__(
"""
self._stt = stt
self._conn_options = conn_options
self._input_ch = aio.Chan[rtc.AudioFrame | RecognizeStream._FlushSentinel]()
self._input_ch = RecognizeStream._InputChan()
self._event_ch = aio.Chan[SpeechEvent]()

self._tee = aio.itertools.tee(self._event_ch, 2)
Expand All @@ -406,7 +470,6 @@ def __init__(
self._pushed_sr = 0
self._resampler: rtc.AudioResampler | None = None

self._start_time_offset: float = 0.0
self._start_time: float = time.time()
self._context: BaseModel | None = None

Expand All @@ -426,13 +489,20 @@ def context(self, value: BaseModel | None) -> None:

@property
def start_time_offset(self) -> float:
return self._start_time_offset
"""Offset plugins add to the provider's timestamps.

Setting it says the caller's timeline began ``value`` seconds ago. With no value
set, the timeline begins with the stream's first audio. The provider counts from
the first frame it reads, and each new connection restarts that count, so the
offset is re-anchored on the first frame each attempt reads.
"""
return self._input_ch.start_time_offset

@start_time_offset.setter
def start_time_offset(self, value: float) -> None:
if value < 0:
raise ValueError("start_time_offset must be non-negative")
self._start_time_offset = value
self._input_ch.start_time_offset = value

@property
def start_time(self) -> float:
Expand Down Expand Up @@ -589,17 +659,14 @@ async def _run(self) -> None: ...

async def _main_task(self) -> None:
max_retries = self._conn_options.max_retry
# we need to record last start time for each run/connection
# so that returned transcripts can have linear timestamps
last_start_time = time.time()

while self._num_retries <= max_retries:
try:
self._start_time_offset += time.time() - last_start_time
self._start_time = time.time()
last_start_time = time.time()
return await self._run()
except (APIError, aiohttp.ClientResponseError) as exception:
# _run has stopped reading, so the next frame read is the next connection's
self._input_ch.restart_provider_clock()
# Some providers use aiohttp directly. Preserve HTTP status and
# retry policy without retaining request headers in the cause.
e = (
Expand Down
18 changes: 15 additions & 3 deletions livekit-agents/livekit/agents/voice/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,9 @@ def stt_node(

You can override this node with your own implementation for more flexibility (e.g.,
custom pre-processing of audio, additional buffering, or alternative STT strategies).
Timestamps in the yielded ``SpeechData`` are relative to the first audio frame the
node consumes, unless the node sets ``start_time_offset`` on its stream; the default
implementation sets it so they are relative to the session start.

If your override buffers audio passed to Agent.default.stt_node, framework
flushing can occur before that audio reaches STT. Set
Expand Down Expand Up @@ -532,10 +535,17 @@ async def stt_node(
try:
conn_options = activity.session.conn_options.stt_conn_options
async with wrapped_stt.stream(conn_options=conn_options) as stream:
_audio_input_started_at: float = (
activity._audio_recognition._input_started_at
# Timestamps are offset onto the session timeline: a new pipeline counts
# from the recording or session start, a recreated stream continues the
# pipeline's timeline. The pipeline anchors them on the same instant.
pipeline = (
activity._audio_recognition._stt_pipeline
if activity._audio_recognition is not None
and activity._audio_recognition._input_started_at is not None
else None
)
_audio_input_started_at: float = (
pipeline.input_started_at
if pipeline is not None and pipeline.input_started_at is not None
else (
activity.session._recorder_io.recording_started_at
if activity.session._recorder_io
Expand All @@ -546,6 +556,8 @@ async def stt_node(
)
)
stream.start_time_offset = time.time() - _audio_input_started_at
if pipeline is not None:
pipeline.input_started_at = _audio_input_started_at

pipeline = _STTPipelineContextVar.get(None)
if pipeline:
Expand Down
Loading
Loading