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
2 changes: 0 additions & 2 deletions livekit-plugins/livekit-plugins-gladia/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ You'll need an API key from Gladia. It can be set as an environment variable: `G
- Multi-language support
- Code-switching between languages
- Interim results (partial transcriptions)
- Voice activity detection with energy filtering
- Optional real-time translation
- Customizable audio parameters (sample rate, bit depth, channels, encoding)

Expand All @@ -45,7 +44,6 @@ stt = GladiaSTT(
channels=1, # Number of audio channels
region="eu-west" # Specify Region to use for the Gladia API
encoding="wav/pcm", # Audio encoding format
energy_filter=True, # Enable voice activity detection
translation_enabled=True,
translation_target_languages=["en"],
translation_model="base",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
See https://docs.livekit.io/agents/integrations/stt/gladia/ for more information.
"""

from .stt import STT, AudioEnergyFilter, SpeechStream
from .stt import STT, SpeechStream
from .version import __version__

__all__ = ["STT", "SpeechStream", "AudioEnergyFilter", "__version__"]
__all__ = ["STT", "SpeechStream", "__version__"]


from livekit.agents import Plugin
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,10 @@
import os
import weakref
from dataclasses import dataclass
from enum import Enum
from typing import Any, Literal
from urllib.parse import urlencode

import aiohttp
import numpy as np

from livekit import rtc
from livekit.agents import (
Expand All @@ -51,45 +49,6 @@

BASE_URL = "https://api.gladia.io/v2/live"

MAGIC_NUMBER_THRESHOLD = 0.004**2


class AudioEnergyFilter:
class State(Enum):
START = 0
SPEAKING = 1
SILENCE = 2
END = 3

def __init__(self, *, min_silence: float = 1.5, rms_threshold: float = MAGIC_NUMBER_THRESHOLD):
self._cooldown_seconds = min_silence
self._cooldown = min_silence
self._state = self.State.SILENCE
self._rms_threshold = rms_threshold

def update(self, frame: rtc.AudioFrame) -> State:
arr = np.frombuffer(frame.data, dtype=np.int16)
float_arr = arr.astype(np.float32) / 32768.0
rms = np.mean(np.square(float_arr))

if rms > self._rms_threshold:
self._cooldown = self._cooldown_seconds
if self._state in (self.State.SILENCE, self.State.END):
self._state = self.State.START
else:
self._state = self.State.SPEAKING
else:
if self._cooldown <= 0:
if self._state in (self.State.SPEAKING, self.State.START):
self._state = self.State.END
elif self._state == self.State.END:
self._state = self.State.SILENCE
else:
self._cooldown -= frame.duration
self._state = self.State.SPEAKING

return self._state


@dataclass
class LanguageConfiguration:
Expand Down Expand Up @@ -130,7 +89,6 @@ class STTOptions:
translation_config: TranslationConfiguration = dataclasses.field(
default_factory=TranslationConfiguration
)
energy_filter: AudioEnergyFilter | bool = False
custom_vocabulary: list[str | dict] | None = None
custom_spelling: dict[str, list[str]] | None = None
pre_processing: PreProcessingConfiguration = dataclasses.field(
Expand Down Expand Up @@ -219,7 +177,6 @@ def __init__(
api_key: str | None = None,
http_session: aiohttp.ClientSession | None = None,
base_url: str = BASE_URL,
energy_filter: AudioEnergyFilter | bool = False,
translation_enabled: bool = False,
translation_target_languages: list[str] | None = None,
translation_model: str = "base",
Expand Down Expand Up @@ -254,8 +211,6 @@ def __init__(
environment variable.
http_session: Optional aiohttp ClientSession to use for requests.
base_url: The base URL for Gladia API. Defaults to "https://api.gladia.io/v2/live".
energy_filter: Audio energy filter configuration for voice activity detection.
Can be a boolean or AudioEnergyFilter instance. Defaults to False.
translation_enabled: Whether to enable translation. Defaults to False.
translation_target_languages: List of target languages for translation.
Required if translation_enabled is True.
Expand Down Expand Up @@ -323,7 +278,6 @@ def __init__(
maximum_duration_without_endpointing=maximum_duration_without_endpointing,
translation_config=translation_config,
pre_processing=pre_processing_config,
energy_filter=energy_filter,
custom_vocabulary=custom_vocabulary,
custom_spelling=custom_spelling,
)
Expand Down Expand Up @@ -750,13 +704,6 @@ def __init__(
duration=5.0,
)

self._audio_energy_filter: AudioEnergyFilter | None = None
if opts.energy_filter:
if isinstance(opts.energy_filter, AudioEnergyFilter):
self._audio_energy_filter = opts.energy_filter
else:
self._audio_energy_filter = AudioEnergyFilter()

self._pushed_audio_duration = 0.0
self._request_id = ""
self._reconnect_event = asyncio.Event()
Expand Down Expand Up @@ -966,7 +913,6 @@ async def _send_audio_task(self) -> None:
)

has_ended = False
last_frame: rtc.AudioFrame | None = None
closing_ws = False

try:
Expand All @@ -976,20 +922,7 @@ async def _send_audio_task(self) -> None:

frames: list[rtc.AudioFrame] = []
if isinstance(data, rtc.AudioFrame):
state = self._check_energy_state(data)
if state in (
AudioEnergyFilter.State.START,
AudioEnergyFilter.State.SPEAKING,
):
if last_frame:
frames.extend(audio_bstream.write(last_frame.data.tobytes()))
last_frame = None
frames.extend(audio_bstream.write(data.data.tobytes()))
elif state == AudioEnergyFilter.State.END:
frames = audio_bstream.flush()
has_ended = True
elif state == AudioEnergyFilter.State.SILENCE:
last_frame = data
frames = audio_bstream.write(data.data.tobytes())
elif isinstance(data, self._FlushSentinel):
frames = audio_bstream.flush()
has_ended = True
Expand Down Expand Up @@ -1205,12 +1138,6 @@ def _process_gladia_message(self, data: dict) -> None:
if self._speaking:
self._speaking = False

def _check_energy_state(self, frame: rtc.AudioFrame) -> AudioEnergyFilter.State:
"""Check the energy state of an audio frame."""
if self._audio_energy_filter:
return self._audio_energy_filter.update(frame)
return AudioEnergyFilter.State.SPEAKING

def _on_audio_duration_report(self, duration: float) -> None:
"""Report the audio duration for usage tracking."""
usage_event = stt.SpeechEvent(
Expand Down
1 change: 0 additions & 1 deletion livekit-plugins/livekit-plugins-gladia/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ classifiers = [
]
dependencies = [
"livekit-agents[codecs]>=1.8.12",
"numpy>=1.26",
"aiohttp>=3.8.0",
]

Expand Down
54 changes: 53 additions & 1 deletion tests/test_plugin_gladia_stt.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from __future__ import annotations

import base64
import json
from types import SimpleNamespace

import pytest

from livekit.agents import stt
from livekit import rtc
from livekit.agents import stt, utils
from livekit.plugins.gladia import stt as gladia_stt

pytestmark = pytest.mark.plugin("gladia")
Expand Down Expand Up @@ -92,3 +95,52 @@ async def test_update_options_rejects_translation_without_target_languages():

stt.update_options(translation_enabled=False, translation_target_languages=[])
assert stt._opts.translation_config.enabled is False


async def test_send_audio_forwards_silence_and_flushes_partial_chunk():
sample_rate = 16000

def _frame(sample: int, duration_ms: int) -> rtc.AudioFrame:
num_samples = sample_rate * duration_ms // 1000
return rtc.AudioFrame(
data=sample.to_bytes(2, "little", signed=True) * num_samples,
sample_rate=sample_rate,
num_channels=1,
samples_per_channel=num_samples,
)

messages: list[dict] = []

async def _send_str(payload: str) -> None:
messages.append(json.loads(payload))

usage: list[float] = []
stream = object.__new__(gladia_stt.SpeechStream)
stream._opts = gladia_stt.STT(api_key="test-key", sample_rate=sample_rate)._opts
stream._ws = SimpleNamespace(send_str=_send_str)
stream._session = SimpleNamespace(closed=False)
stream._input_ch = utils.aio.Chan()
stream._audio_duration_collector = gladia_stt.PeriodicCollector(
callback=usage.append, duration=5.0
)

# speech and silence share 100 ms chunks, and 30 ms of trailing silence stays buffered
pushed = [_frame(1000, 50), _frame(0, 100), _frame(1000, 50), _frame(0, 30)]
for frame in pushed:
stream._input_ch.send_nowait(frame)
stream._input_ch.send_nowait(gladia_stt.SpeechStream._FlushSentinel())
stream._input_ch.close()

await stream._send_audio_task()

assert [m["type"] for m in messages] == [
"audio_chunk",
"audio_chunk",
"audio_chunk",
"stop_recording", # explicit flush
"stop_recording", # end of input
]
chunks = [base64.b64decode(m["data"]["chunk"]) for m in messages[:3]]
assert [len(chunk) for chunk in chunks] == [3200, 3200, 960]
assert b"".join(chunks) == b"".join(frame.data.tobytes() for frame in pushed)
assert sum(usage) == pytest.approx(0.23)
2 changes: 0 additions & 2 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading