livekit-plugins-tts-cache-router 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,62 @@
1
+ # Copyright 2026 Oggnai Technologies Private Limited
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """tts-cache-router plugin for LiveKit Agents.
16
+
17
+ Serves repeated sentences from a per-account cache and synthesizes the rest at Sarvam, Raya or
18
+ ElevenLabs with your own provider key. See https://docs.ttscacherouter.dev/livekit.
19
+ """
20
+
21
+ from .providers import (
22
+ ElevenLabs,
23
+ PronunciationDictionaryLocator,
24
+ Raya,
25
+ Sarvam,
26
+ VoiceSettings,
27
+ )
28
+ from .tts import TTS, ChunkedStream, SynthesizeStream
29
+ from .version import __version__
30
+
31
+ __all__ = [
32
+ "TTS",
33
+ "ChunkedStream",
34
+ "SynthesizeStream",
35
+ "Sarvam",
36
+ "Raya",
37
+ "ElevenLabs",
38
+ "VoiceSettings",
39
+ "PronunciationDictionaryLocator",
40
+ "__version__",
41
+ ]
42
+
43
+ from livekit.agents import Plugin
44
+
45
+ from .log import logger
46
+
47
+
48
+ class TTSCacheRouterPlugin(Plugin):
49
+ def __init__(self) -> None:
50
+ super().__init__(__name__, __version__, __package__, logger)
51
+
52
+
53
+ Plugin.register_plugin(TTSCacheRouterPlugin())
54
+
55
+ # Cleanup docs of unexported modules
56
+ _module = dir()
57
+ NOT_IN_ALL = [m for m in _module if m not in __all__]
58
+
59
+ __pdoc__ = {}
60
+
61
+ for n in NOT_IN_ALL:
62
+ __pdoc__[n] = False
@@ -0,0 +1,3 @@
1
+ import logging
2
+
3
+ logger = logging.getLogger("livekit.plugins.tts_cache_router")
@@ -0,0 +1,319 @@
1
+ # Copyright 2026 Oggnai Technologies Private Limited
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """The provider the router synthesizes with, in that provider's own parameter names."""
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass
20
+ from typing import Any, Literal
21
+
22
+ from livekit.agents import LanguageCode
23
+
24
+ SarvamModels = Literal["bulbul:v3", "bulbul:v4-flash"]
25
+ RayaModels = Literal["m1", "standard"]
26
+ ElevenLabsModels = Literal[
27
+ "eleven_flash_v2_5",
28
+ "eleven_turbo_v2_5",
29
+ "eleven_multilingual_v2",
30
+ "eleven_flash_v2",
31
+ "eleven_turbo_v2",
32
+ "eleven_v3",
33
+ "eleven_v3_conversational",
34
+ "eleven_v4",
35
+ "eleven_v4_turbo",
36
+ ]
37
+ _ELEVENLABS_MODELS = ElevenLabsModels.__args__ # type: ignore[attr-defined]
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Sarvam:
42
+ """Sarvam Bulbul. The router calls Sarvam with the Sarvam API key stored for your org in
43
+ the dashboard.
44
+
45
+ Args:
46
+ model: ``"bulbul:v3"`` or ``"bulbul:v4-flash"``.
47
+ speaker: Sarvam speaker id, e.g. ``"shubh"``. Must belong to ``model``.
48
+ language: Sarvam language code, e.g. ``"hi-IN"``.
49
+ pace: Speech speed, 0.5–2.0.
50
+ temperature: Sampling temperature, 0.01–1.0.
51
+ dict_id: Optional pronunciation dictionary id.
52
+ pitch: ``bulbul:v4-flash`` only: -0.5 (deeper) to 0.5 (higher); Sarvam's default is 0.
53
+ loudness: ``bulbul:v4-flash`` only: 0.1–2.5; Sarvam's default is 1.0.
54
+ enable_preprocessing: ``bulbul:v4-flash`` only: normalize numbers and English words in
55
+ the text before synthesis.
56
+ min_buffer_size: Characters Sarvam buffers before it starts synthesizing, 30–200.
57
+ Defaults to the least Sarvam allows.
58
+ max_chunk_length: The longest text Sarvam synthesizes in one piece, 50–500; it splits
59
+ longer sentences. Defaults to the most Sarvam allows, so each sentence is synthesized
60
+ whole.
61
+ """
62
+
63
+ model: SarvamModels
64
+ speaker: str
65
+ language: str
66
+ pace: float = 1.0
67
+ temperature: float = 0.6
68
+ dict_id: str | None = None
69
+ pitch: float | None = None
70
+ loudness: float | None = None
71
+ enable_preprocessing: bool | None = None
72
+ min_buffer_size: int | None = None
73
+ max_chunk_length: int | None = None
74
+
75
+ def __post_init__(self) -> None:
76
+ if self.model not in ("bulbul:v3", "bulbul:v4-flash"):
77
+ raise ValueError(
78
+ f"Sarvam model must be bulbul:v3 or bulbul:v4-flash, got {self.model!r}"
79
+ )
80
+ if not 0.5 <= self.pace <= 2.0:
81
+ raise ValueError(f"Sarvam pace must be between 0.5 and 2.0, got {self.pace}")
82
+ if not 0.01 <= self.temperature <= 1.0:
83
+ raise ValueError(
84
+ f"Sarvam temperature must be between 0.01 and 1.0, got {self.temperature}"
85
+ )
86
+ v4_only = {
87
+ "pitch": self.pitch,
88
+ "loudness": self.loudness,
89
+ "enable_preprocessing": self.enable_preprocessing,
90
+ }
91
+ given = [name for name, value in v4_only.items() if value is not None]
92
+ if given and self.model != "bulbul:v4-flash":
93
+ raise ValueError(f"Sarvam {', '.join(given)} need model bulbul:v4-flash")
94
+ if self.pitch is not None and not -0.5 <= self.pitch <= 0.5:
95
+ raise ValueError(f"Sarvam pitch must be between -0.5 and 0.5, got {self.pitch}")
96
+ if self.loudness is not None and not 0.1 <= self.loudness <= 2.5:
97
+ raise ValueError(f"Sarvam loudness must be between 0.1 and 2.5, got {self.loudness}")
98
+ if self.min_buffer_size is not None and not 30 <= self.min_buffer_size <= 200:
99
+ raise ValueError(
100
+ f"Sarvam min_buffer_size must be between 30 and 200, got {self.min_buffer_size}"
101
+ )
102
+ if self.max_chunk_length is not None and not 50 <= self.max_chunk_length <= 500:
103
+ raise ValueError(
104
+ f"Sarvam max_chunk_length must be between 50 and 500, got {self.max_chunk_length}"
105
+ )
106
+
107
+ @property
108
+ def provider_name(self) -> str:
109
+ return "Sarvam"
110
+
111
+ @property
112
+ def _sends_words(self) -> bool:
113
+ return False
114
+
115
+ def _start_fields(self) -> dict[str, Any]:
116
+ return {
117
+ "provider": "sarvam",
118
+ "model": self.model,
119
+ "voice": self.speaker,
120
+ "language": self.language,
121
+ "speed": self.pace,
122
+ "options": {
123
+ "temperature": self.temperature,
124
+ "dict_id": self.dict_id,
125
+ **{
126
+ name: value
127
+ for name, value in (
128
+ ("pitch", self.pitch),
129
+ ("loudness", self.loudness),
130
+ ("enable_preprocessing", self.enable_preprocessing),
131
+ ("min_buffer_size", self.min_buffer_size),
132
+ ("max_chunk_length", self.max_chunk_length),
133
+ )
134
+ if value is not None
135
+ },
136
+ },
137
+ }
138
+
139
+
140
+ @dataclass(frozen=True)
141
+ class Raya:
142
+ """Raya Bakbak. The router calls Raya with the Raya API key stored for your org in the
143
+ dashboard.
144
+
145
+ Args:
146
+ model: ``"standard"`` or ``"m1"``.
147
+ voice_id: Raya voice id. Must belong to ``model``.
148
+ language: Raya language code, e.g. ``"hi"``.
149
+ speed: Speech speed, 0.5–1.5.
150
+ """
151
+
152
+ model: RayaModels
153
+ voice_id: str
154
+ language: str
155
+ speed: float = 1.0
156
+
157
+ def __post_init__(self) -> None:
158
+ if self.model not in ("m1", "standard"):
159
+ raise ValueError(f"Raya model must be m1 or standard, got {self.model!r}")
160
+ if not 0.5 <= self.speed <= 1.5:
161
+ raise ValueError(f"Raya speed must be between 0.5 and 1.5, got {self.speed}")
162
+
163
+ @property
164
+ def provider_name(self) -> str:
165
+ return "Raya"
166
+
167
+ @property
168
+ def _sends_words(self) -> bool:
169
+ return False
170
+
171
+ def _start_fields(self) -> dict[str, Any]:
172
+ return {
173
+ "provider": "raya",
174
+ "model": self.model,
175
+ "voice": self.voice_id,
176
+ "language": self.language,
177
+ "speed": self.speed,
178
+ "options": {},
179
+ }
180
+
181
+
182
+ @dataclass(frozen=True)
183
+ class VoiceSettings:
184
+ """ElevenLabs voice settings, as in ElevenLabs' LiveKit plugin.
185
+
186
+ Args:
187
+ stability: 0.0–1.0.
188
+ similarity_boost: 0.0–1.0.
189
+ style: 0.0–1.0.
190
+ speed: 0.7–1.2.
191
+ use_speaker_boost: Boost similarity to the original speaker.
192
+ """
193
+
194
+ stability: float
195
+ similarity_boost: float
196
+ style: float | None = None
197
+ speed: float | None = None
198
+ use_speaker_boost: bool | None = None
199
+
200
+ def __post_init__(self) -> None:
201
+ for name in ("stability", "similarity_boost", "style"):
202
+ value = getattr(self, name)
203
+ if value is not None and not 0.0 <= value <= 1.0:
204
+ raise ValueError(f"ElevenLabs {name} must be between 0.0 and 1.0, got {value}")
205
+ if self.speed is not None and not 0.7 <= self.speed <= 1.2:
206
+ raise ValueError(f"ElevenLabs speed must be between 0.7 and 1.2, got {self.speed}")
207
+
208
+ def _fields(self) -> dict[str, Any]:
209
+ fields: dict[str, Any] = {
210
+ "stability": self.stability,
211
+ "similarity_boost": self.similarity_boost,
212
+ }
213
+ for name in ("style", "speed", "use_speaker_boost"):
214
+ if getattr(self, name) is not None:
215
+ fields[name] = getattr(self, name)
216
+ return fields
217
+
218
+
219
+ @dataclass(frozen=True)
220
+ class PronunciationDictionaryLocator:
221
+ """An ElevenLabs pronunciation dictionary version."""
222
+
223
+ pronunciation_dictionary_id: str
224
+ version_id: str
225
+
226
+
227
+ @dataclass(frozen=True)
228
+ class ElevenLabs:
229
+ """ElevenLabs, with the settings of ElevenLabs' own LiveKit plugin. The router calls
230
+ ElevenLabs with the ElevenLabs API key stored for your org in the dashboard.
231
+
232
+ Args:
233
+ voice_id: ElevenLabs voice id.
234
+ model: ElevenLabs model, e.g. ``"eleven_flash_v2_5"``. ``eleven_v3`` and ``eleven_v4``
235
+ models go through ElevenLabs' text-to-dialogue API.
236
+ language: Optional language to enforce, e.g. ``"en"`` (``"en-US"`` and ``"english"``
237
+ are read as ``"en"``, as ElevenLabs' plugin reads them).
238
+ voice_settings: Optional voice settings; the voice's stored settings otherwise.
239
+ apply_text_normalization: ``"auto"``, ``"on"`` or ``"off"``.
240
+ apply_language_text_normalization: Language-specific normalization (Japanese).
241
+ enable_ssml_parsing: Parse SSML tags in the text.
242
+ enable_logging: ``False`` uses ElevenLabs' zero-retention mode (enterprise accounts).
243
+ pronunciation_dictionary_locators: Up to 3 pronunciation dictionaries.
244
+ sync_alignment: Word-level timed transcripts.
245
+ preferred_alignment: ``"normalized"`` or ``"original"`` text for the word timings;
246
+ ``"original"`` for Japanese, Korean and Chinese by default, else ``"normalized"``.
247
+ """
248
+
249
+ voice_id: str
250
+ model: ElevenLabsModels = "eleven_turbo_v2_5"
251
+ language: str | None = None
252
+ voice_settings: VoiceSettings | None = None
253
+ apply_text_normalization: Literal["auto", "on", "off"] = "auto"
254
+ apply_language_text_normalization: bool | None = None
255
+ enable_ssml_parsing: bool = False
256
+ enable_logging: bool = True
257
+ pronunciation_dictionary_locators: tuple[PronunciationDictionaryLocator, ...] = ()
258
+ sync_alignment: bool = True
259
+ preferred_alignment: Literal["normalized", "original"] | None = None
260
+
261
+ def __post_init__(self) -> None:
262
+ if self.model not in _ELEVENLABS_MODELS:
263
+ raise ValueError(
264
+ f"ElevenLabs model must be one of {', '.join(_ELEVENLABS_MODELS)}, "
265
+ f"got {self.model!r}"
266
+ )
267
+ if self.apply_text_normalization not in ("auto", "on", "off"):
268
+ raise ValueError(
269
+ "ElevenLabs apply_text_normalization must be auto, on or off, "
270
+ f"got {self.apply_text_normalization!r}"
271
+ )
272
+ if len(self.pronunciation_dictionary_locators) > 3:
273
+ raise ValueError("ElevenLabs takes at most 3 pronunciation dictionaries")
274
+ # A list is accepted too; keep the dataclass hashable.
275
+ object.__setattr__(
276
+ self,
277
+ "pronunciation_dictionary_locators",
278
+ tuple(self.pronunciation_dictionary_locators),
279
+ )
280
+
281
+ @property
282
+ def provider_name(self) -> str:
283
+ return "ElevenLabs"
284
+
285
+ @property
286
+ def _sends_words(self) -> bool:
287
+ return self.sync_alignment
288
+
289
+ def _start_fields(self) -> dict[str, Any]:
290
+ options: dict[str, Any] = {
291
+ "apply_text_normalization": self.apply_text_normalization,
292
+ "enable_ssml_parsing": self.enable_ssml_parsing,
293
+ "enable_logging": self.enable_logging,
294
+ "sync_alignment": self.sync_alignment,
295
+ }
296
+ if self.voice_settings is not None:
297
+ options["voice_settings"] = self.voice_settings._fields()
298
+ if self.apply_language_text_normalization is not None:
299
+ options["apply_language_text_normalization"] = self.apply_language_text_normalization
300
+ if self.pronunciation_dictionary_locators:
301
+ options["pronunciation_dictionary_locators"] = [
302
+ {
303
+ "pronunciation_dictionary_id": d.pronunciation_dictionary_id,
304
+ "version_id": d.version_id,
305
+ }
306
+ for d in self.pronunciation_dictionary_locators
307
+ ]
308
+ if self.preferred_alignment is not None:
309
+ options["preferred_alignment"] = self.preferred_alignment
310
+ fields: dict[str, Any] = {
311
+ "provider": "elevenlabs",
312
+ "model": self.model,
313
+ "voice": self.voice_id,
314
+ "options": options,
315
+ }
316
+ if self.language is not None:
317
+ # ElevenLabs takes ISO 639-1 codes; its LiveKit plugin sends the language this way.
318
+ fields["language"] = LanguageCode(self.language).language
319
+ return fields
File without changes
@@ -0,0 +1,517 @@
1
+ # Copyright 2026 Oggnai Technologies Private Limited
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import dataclasses
19
+ import json
20
+ import os
21
+ import time
22
+ import weakref
23
+ from collections.abc import AsyncIterable
24
+ from typing import Any, cast
25
+
26
+ import aiohttp
27
+ from livekit.agents import (
28
+ APIConnectionError,
29
+ APIError,
30
+ APIStatusError,
31
+ APITimeoutError,
32
+ tts,
33
+ utils,
34
+ )
35
+ from livekit.agents.metrics import TTSMetrics
36
+ from livekit.agents.metrics.base import Metadata
37
+ from livekit.agents.types import (
38
+ DEFAULT_API_CONNECT_OPTIONS,
39
+ NOT_GIVEN,
40
+ APIConnectOptions,
41
+ NotGivenOr,
42
+ TimedString,
43
+ )
44
+ from livekit.agents.utils import is_given
45
+
46
+ from .log import logger
47
+ from .providers import ElevenLabs, Raya, Sarvam
48
+
49
+ DEFAULT_BASE_URL = "wss://api.ttscacherouter.dev"
50
+ API_KEY_ENV = "TTS_CACHE_ROUTER_API_KEY"
51
+ SUPPORTED_SAMPLE_RATES = (8000, 16000, 22050, 24000)
52
+ # ElevenLabs also streams these.
53
+ ELEVENLABS_SAMPLE_RATES = (8000, 16000, 22050, 24000, 32000, 44100, 48000)
54
+
55
+ # The router closes connections idle for longer than its idle timeout (300 s on the hosted
56
+ # router); pooled sockets are retired well before that.
57
+ _MAX_SESSION_DURATION = 240
58
+
59
+ # After a barge-in, how long to wait for the router to confirm the cancel before giving up on
60
+ # reusing the connection.
61
+ _CANCEL_TIMEOUT_S = 2.0
62
+
63
+ # Router error code → HTTP-like status, when the provider gave none.
64
+ _STATUS_FOR_CODE = {
65
+ "bad_request": 400,
66
+ "unauthorized": 401,
67
+ "insufficient_credits": 402,
68
+ "provider_key_missing": 400,
69
+ "provider_rejected": 400,
70
+ "provider_rate_limited": 429,
71
+ "provider_unavailable": 502,
72
+ "provider_timeout": 504,
73
+ "internal": 500,
74
+ }
75
+
76
+
77
+ class TTS(tts.TTS[Any]):
78
+ def __init__(
79
+ self,
80
+ *,
81
+ provider: Sarvam | Raya | ElevenLabs,
82
+ api_key: str | None = None,
83
+ base_url: str = DEFAULT_BASE_URL,
84
+ sample_rate: int = 24000,
85
+ http_session: aiohttp.ClientSession | None = None,
86
+ ) -> None:
87
+ """Text-to-speech through tts-cache-router.
88
+
89
+ Sentences your org has synthesized before with the same voice and settings are replayed
90
+ from its cache; the rest are synthesized by the provider with the provider key stored for
91
+ your org in the dashboard. The audio is the provider's own: a cache hit replays a real
92
+ take for that exact request.
93
+
94
+ Args:
95
+ provider: ``Sarvam(...)``, ``Raya(...)`` or ``ElevenLabs(...)``: the provider, voice
96
+ and settings to use.
97
+ api_key: Router API key. Defaults to the ``TTS_CACHE_ROUTER_API_KEY`` environment
98
+ variable.
99
+ base_url: Router URL. Defaults to the hosted router.
100
+ sample_rate: 8000, 16000, 22050 or 24000; ElevenLabs also 32000, 44100 or 48000.
101
+ http_session: Optional aiohttp session; defaults to the job's.
102
+ """
103
+ super().__init__(
104
+ capabilities=tts.TTSCapabilities(streaming=True, aligned_transcript=True),
105
+ sample_rate=sample_rate,
106
+ num_channels=1,
107
+ )
108
+ router_key = api_key or os.environ.get(API_KEY_ENV)
109
+ if not router_key:
110
+ raise ValueError(
111
+ f"tts-cache-router API key is required, either as api_key or set {API_KEY_ENV}"
112
+ )
113
+ _check_sample_rate(provider, sample_rate)
114
+
115
+ self._provider = provider
116
+ self._api_key = router_key
117
+ self._url = f"{base_url.rstrip('/')}/v1/stream"
118
+ self._session = http_session
119
+ self._pool = utils.ConnectionPool[aiohttp.ClientWebSocketResponse](
120
+ connect_cb=self._connect_ws,
121
+ close_cb=self._close_ws,
122
+ max_session_duration=_MAX_SESSION_DURATION,
123
+ mark_refreshed_on_get=True,
124
+ )
125
+ self._streams = weakref.WeakSet[SynthesizeStream]()
126
+ self._background: set[asyncio.Task[Any]] = set()
127
+
128
+ def update_options(
129
+ self,
130
+ *,
131
+ provider: NotGivenOr[Sarvam | Raya | ElevenLabs] = NOT_GIVEN,
132
+ **settings: Any,
133
+ ) -> None:
134
+ """Change the provider or its settings. Segments that start from now on use them.
135
+
136
+ Args:
137
+ provider: A new ``Sarvam(...)``, ``Raya(...)`` or ``ElevenLabs(...)``.
138
+ **settings: Settings of the provider to change, in its own names, e.g.
139
+ ``update_options(speaker="priya", pace=1.1)`` for Sarvam or
140
+ ``update_options(voice_id="…")`` for ElevenLabs.
141
+ """
142
+ new = provider if is_given(provider) else self._provider
143
+ if settings:
144
+ # Validated by the provider's own constructor.
145
+ new = dataclasses.replace(new, **settings)
146
+ _check_sample_rate(new, self.sample_rate)
147
+ self._provider = new
148
+
149
+ @property
150
+ def model(self) -> str:
151
+ return self._provider.model
152
+
153
+ @property
154
+ def provider(self) -> str:
155
+ # The underlying provider, so usage dashboards attribute cost to whoever charges for it.
156
+ return self._provider.provider_name
157
+
158
+ def _ensure_session(self) -> aiohttp.ClientSession:
159
+ if not self._session:
160
+ self._session = utils.http_context.http_session()
161
+ return self._session
162
+
163
+ async def _connect_ws(self, timeout: float) -> aiohttp.ClientWebSocketResponse:
164
+ async def connect() -> aiohttp.ClientWebSocketResponse:
165
+ ws = await self._ensure_session().ws_connect(
166
+ self._url, headers={"Authorization": f"Bearer {self._api_key}"}
167
+ )
168
+ # aiohttp types text frames per `decode_text`; this module reads them as str.
169
+ return cast(aiohttp.ClientWebSocketResponse, ws)
170
+
171
+ try:
172
+ return await asyncio.wait_for(connect(), timeout)
173
+ except asyncio.TimeoutError:
174
+ raise APITimeoutError("timed out connecting to tts-cache-router") from None
175
+ except aiohttp.WSServerHandshakeError as e:
176
+ if e.status == 403:
177
+ raise APIStatusError(
178
+ "tts-cache-router refused the account key",
179
+ status_code=403,
180
+ retryable=False,
181
+ ) from None
182
+ if e.status == 402:
183
+ raise APIStatusError(
184
+ "tts-cache-router: this org is out of credit, so new connections are refused;"
185
+ " buy credit in the dashboard (Billing)",
186
+ status_code=402,
187
+ retryable=False,
188
+ ) from None
189
+ raise APIStatusError(
190
+ f"tts-cache-router refused the connection: {e.message}",
191
+ status_code=e.status,
192
+ ) from None
193
+ except Exception as e:
194
+ raise APIConnectionError(
195
+ f"connecting to tts-cache-router failed: {type(e).__name__}"
196
+ ) from None
197
+
198
+ async def _close_ws(self, ws: aiohttp.ClientWebSocketResponse) -> None:
199
+ await ws.close()
200
+
201
+ def _in_background(self, coro: Any) -> None:
202
+ task = asyncio.create_task(coro)
203
+ self._background.add(task)
204
+ task.add_done_callback(self._background.discard)
205
+
206
+ def _discard(self, ws: aiohttp.ClientWebSocketResponse) -> None:
207
+ # Closing promptly tells the router the client is gone, so it stops sending audio nobody
208
+ # will play. The pool would otherwise close it only on its next use.
209
+ self._pool.remove(ws)
210
+ self._in_background(ws.close())
211
+
212
+ async def _cancel_segment(self, ws: aiohttp.ClientWebSocketResponse, segment_id: str) -> None:
213
+ """Barge-in: stop the segment but keep the connection warm for the next turn. Audio
214
+ still in flight for the segment is discarded until the router confirms the cancel."""
215
+
216
+ async def confirmed() -> None:
217
+ await ws.send_str(json.dumps({"type": "cancel", "segment_id": segment_id}))
218
+ while True:
219
+ msg = await ws.receive()
220
+ if msg.type == aiohttp.WSMsgType.BINARY:
221
+ continue
222
+ if msg.type != aiohttp.WSMsgType.TEXT:
223
+ raise ConnectionError("tts-cache-router closed the connection")
224
+ data = json.loads(msg.data)
225
+ if data["type"] == "cancelled" and data["segment_id"] == segment_id:
226
+ return
227
+ if data["type"] == "error":
228
+ raise ConnectionError(f"tts-cache-router error {data['code']}")
229
+
230
+ try:
231
+ await asyncio.wait_for(confirmed(), _CANCEL_TIMEOUT_S)
232
+ except Exception as e:
233
+ logger.debug(
234
+ "could not reuse the connection after a cancel",
235
+ extra={"error": type(e).__name__},
236
+ )
237
+ self._discard(ws)
238
+ return
239
+ self._pool.put(ws)
240
+
241
+ def prewarm(self) -> None:
242
+ self._pool.prewarm()
243
+
244
+ def synthesize(
245
+ self,
246
+ text: str,
247
+ *,
248
+ conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
249
+ ) -> ChunkedStream:
250
+ return ChunkedStream(tts=self, input_text=text, conn_options=conn_options)
251
+
252
+ def stream(
253
+ self, *, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS
254
+ ) -> SynthesizeStream:
255
+ stream = SynthesizeStream(tts=self, conn_options=conn_options)
256
+ self._streams.add(stream)
257
+ return stream
258
+
259
+ async def aclose(self) -> None:
260
+ for stream in list(self._streams):
261
+ await stream.aclose()
262
+ self._streams.clear()
263
+ await utils.aio.gracefully_cancel(*self._background)
264
+ await self._pool.aclose()
265
+
266
+ def _start_message(
267
+ self, segment_id: str, provider: Sarvam | Raya | ElevenLabs
268
+ ) -> dict[str, Any]:
269
+ return {
270
+ "type": "start",
271
+ "segment_id": segment_id,
272
+ "sample_rate": self.sample_rate,
273
+ "format": "pcm",
274
+ **provider._start_fields(),
275
+ }
276
+
277
+
278
+ def _check_sample_rate(provider: Sarvam | Raya | ElevenLabs, sample_rate: int) -> None:
279
+ rates = ELEVENLABS_SAMPLE_RATES if isinstance(provider, ElevenLabs) else SUPPORTED_SAMPLE_RATES
280
+ if sample_rate not in rates:
281
+ raise ValueError(
282
+ f"sample_rate must be one of {rates} for {provider.provider_name}, got {sample_rate}"
283
+ )
284
+
285
+
286
+ def _router_error(data: dict[str, Any]) -> APIError:
287
+ status = data.get("provider_status") or _STATUS_FOR_CODE.get(data["code"], 500)
288
+ return APIStatusError(
289
+ f"tts-cache-router {data['code']}: {data['message']}",
290
+ status_code=status,
291
+ body=data,
292
+ retryable=bool(data["retryable"]),
293
+ )
294
+
295
+
296
+ def _initialize(output_emitter: tts.AudioEmitter, sample_rate: int, *, streamed: bool) -> str:
297
+ """Returns the request id."""
298
+ request_id = utils.shortuuid()
299
+ output_emitter.initialize(
300
+ request_id=request_id,
301
+ sample_rate=sample_rate,
302
+ num_channels=1,
303
+ mime_type="audio/pcm",
304
+ stream=streamed,
305
+ )
306
+ return request_id
307
+
308
+
309
+ async def _run_segment(
310
+ stream: SynthesizeStream | ChunkedStream,
311
+ output_emitter: tts.AudioEmitter,
312
+ *,
313
+ request_id: str,
314
+ send_input: Any,
315
+ streamed: bool,
316
+ ) -> None:
317
+ """One router segment: `start`, text, `flush`, then audio until `done`.
318
+
319
+ `send_input(ws, segment_id, first_text_at)` sends the `text` messages and the `flush`.
320
+ """
321
+ router_tts: TTS = stream._tts
322
+ conn_options = stream._conn_options
323
+ sample_rate = router_tts.sample_rate
324
+ segment_id = utils.shortuuid()
325
+ # The settings as of the segment's start: update_options applies from the next segment.
326
+ provider = router_tts._provider
327
+ if streamed:
328
+ output_emitter.start_segment(segment_id=segment_id)
329
+
330
+ started = time.perf_counter()
331
+ first_text_at: list[float] = []
332
+ first_audio_at: float | None = None
333
+ pushed_bytes = 0
334
+ done: dict[str, Any] | None = None
335
+ # With word timings (ElevenLabs), transcripts follow the words; else each sentence.
336
+ words = provider._sends_words
337
+ sentence_start = 0.0
338
+
339
+ async def sender(ws: aiohttp.ClientWebSocketResponse) -> None:
340
+ await ws.send_str(json.dumps(router_tts._start_message(segment_id, provider)))
341
+ await send_input(ws, segment_id, first_text_at)
342
+
343
+ pool = router_tts._pool
344
+ try:
345
+ ws = await pool.get(timeout=conn_options.timeout)
346
+ except APIError:
347
+ raise
348
+ except Exception as e:
349
+ raise APIConnectionError(
350
+ f"connecting to tts-cache-router failed: {type(e).__name__}"
351
+ ) from e
352
+ stream._acquire_time = pool.last_acquire_time
353
+ stream._connection_reused = pool.last_connection_reused
354
+ send_task = asyncio.create_task(sender(ws))
355
+ try:
356
+ while done is None:
357
+ try:
358
+ msg = await ws.receive(timeout=conn_options.timeout)
359
+ except asyncio.TimeoutError:
360
+ # Until all input is sent, silence just means the LLM is still talking.
361
+ if send_task.done():
362
+ send_task.result()
363
+ raise APITimeoutError("tts-cache-router sent nothing in time") from None
364
+ continue
365
+
366
+ if msg.type == aiohttp.WSMsgType.BINARY:
367
+ if first_audio_at is None:
368
+ first_audio_at = time.perf_counter()
369
+ pushed_bytes += len(msg.data)
370
+ output_emitter.push(msg.data)
371
+ continue
372
+ if msg.type != aiohttp.WSMsgType.TEXT:
373
+ raise APIConnectionError("tts-cache-router closed the connection")
374
+
375
+ data = json.loads(msg.data)
376
+ if data["type"] == "sentence":
377
+ sentence_start = pushed_bytes / 2 / sample_rate
378
+ if not words:
379
+ # Transcripts stay in step with speech at sentence granularity.
380
+ output_emitter.push_timed_transcript(
381
+ TimedString(text=data["text"] + " ", start_time=sentence_start)
382
+ )
383
+ elif data["type"] == "words":
384
+ # Word by word, as ElevenLabs' own plugin aligns them.
385
+ output_emitter.push_timed_transcript(
386
+ [
387
+ TimedString(
388
+ text=w["text"],
389
+ start_time=sentence_start + w["start"],
390
+ end_time=sentence_start + w["end"],
391
+ )
392
+ for w in data["words"]
393
+ ]
394
+ )
395
+ elif data["type"] == "done":
396
+ done = data
397
+ elif data["type"] == "error":
398
+ raise _router_error(data)
399
+ else:
400
+ logger.warning("unexpected tts-cache-router message", extra={"type": data["type"]})
401
+ send_task.result()
402
+ except asyncio.CancelledError:
403
+ # Barge-in. The `start` may already be out, so ask the router to cancel the segment (a
404
+ # no-op it still confirms if the segment never started or already finished), and return
405
+ # the warm connection to the pool once it confirms.
406
+ await utils.aio.gracefully_cancel(send_task)
407
+ router_tts._in_background(router_tts._cancel_segment(ws, segment_id))
408
+ raise
409
+ except APIError:
410
+ router_tts._discard(ws)
411
+ raise
412
+ except Exception as e:
413
+ router_tts._discard(ws)
414
+ raise APIConnectionError(f"tts-cache-router connection failed: {type(e).__name__}") from e
415
+ finally:
416
+ await utils.aio.gracefully_cancel(send_task)
417
+ pool.put(ws)
418
+
419
+ if streamed:
420
+ output_emitter.end_segment()
421
+ else:
422
+ output_emitter.flush()
423
+
424
+ # Cache hits are not provider characters: report only what the provider billed.
425
+ ttfb = first_audio_at - first_text_at[0] if first_audio_at and first_text_at else -1.0
426
+ router_tts.emit(
427
+ "metrics_collected",
428
+ TTSMetrics(
429
+ timestamp=time.time(),
430
+ request_id=request_id,
431
+ segment_id=segment_id if streamed else None,
432
+ ttfb=ttfb,
433
+ duration=time.perf_counter() - started,
434
+ characters_count=done["billed_characters"],
435
+ audio_duration=pushed_bytes / 2 / sample_rate,
436
+ cancelled=False,
437
+ label=router_tts.label,
438
+ streamed=streamed,
439
+ acquire_time=stream._acquire_time,
440
+ connection_reused=stream._connection_reused,
441
+ metadata=Metadata(model_name=provider.model, model_provider=provider.provider_name),
442
+ ),
443
+ )
444
+
445
+
446
+ class ChunkedStream(tts.ChunkedStream):
447
+ def __init__(self, *, tts: TTS, input_text: str, conn_options: APIConnectOptions) -> None:
448
+ super().__init__(tts=tts, input_text=input_text, conn_options=conn_options)
449
+ self._tts: TTS = tts
450
+
451
+ # Overrides a private method (verified on livekit-agents 1.8.5): the base class reports
452
+ # len(input_text) as provider characters, which would bill cache hits. _run_segment emits
453
+ # the metrics with the router's billed_characters instead.
454
+ async def _metrics_monitor_task(self, event_aiter: AsyncIterable[tts.SynthesizedAudio]) -> None:
455
+ async for _ in event_aiter:
456
+ pass
457
+
458
+ async def _run(self, output_emitter: tts.AudioEmitter) -> None:
459
+ async def send_input(
460
+ ws: aiohttp.ClientWebSocketResponse,
461
+ segment_id: str,
462
+ first_text_at: list[float],
463
+ ) -> None:
464
+ if self._input_text:
465
+ first_text_at.append(time.perf_counter())
466
+ await ws.send_str(
467
+ json.dumps(
468
+ {
469
+ "type": "text",
470
+ "segment_id": segment_id,
471
+ "text": self._input_text,
472
+ }
473
+ )
474
+ )
475
+ await ws.send_str(json.dumps({"type": "flush", "segment_id": segment_id}))
476
+
477
+ request_id = _initialize(output_emitter, self._tts.sample_rate, streamed=False)
478
+ await _run_segment(
479
+ self, output_emitter, request_id=request_id, send_input=send_input, streamed=False
480
+ )
481
+
482
+
483
+ class SynthesizeStream(tts.SynthesizeStream):
484
+ def __init__(self, *, tts: TTS, conn_options: APIConnectOptions) -> None:
485
+ super().__init__(tts=tts, conn_options=conn_options)
486
+ self._tts: TTS = tts
487
+
488
+ # Overrides a private method (verified on livekit-agents 1.8.5): the base class reports
489
+ # len(text) as provider characters, which would bill cache hits. _run_segment emits the
490
+ # metrics with the router's billed_characters instead.
491
+ async def _metrics_monitor_task(self, event_aiter: AsyncIterable[tts.SynthesizedAudio]) -> None:
492
+ async for _ in event_aiter:
493
+ pass
494
+
495
+ async def _run(self, output_emitter: tts.AudioEmitter) -> None:
496
+ async def send_input(
497
+ ws: aiohttp.ClientWebSocketResponse,
498
+ segment_id: str,
499
+ first_text_at: list[float],
500
+ ) -> None:
501
+ # One stream is one router segment: livekit-agents passes on no text after the first
502
+ # flush (one SynthesizeStream per segment).
503
+ async for data in self._input_ch:
504
+ if isinstance(data, self._FlushSentinel):
505
+ break
506
+ if not first_text_at:
507
+ first_text_at.append(time.perf_counter())
508
+ self._mark_started()
509
+ await ws.send_str(
510
+ json.dumps({"type": "text", "segment_id": segment_id, "text": data})
511
+ )
512
+ await ws.send_str(json.dumps({"type": "flush", "segment_id": segment_id}))
513
+
514
+ request_id = _initialize(output_emitter, self._tts.sample_rate, streamed=True)
515
+ await _run_segment(
516
+ self, output_emitter, request_id=request_id, send_input=send_input, streamed=True
517
+ )
@@ -0,0 +1,15 @@
1
+ # Copyright 2026 Oggnai Technologies Private Limited
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ __version__ = "0.1.0"
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.5
2
+ Name: livekit-plugins-tts-cache-router
3
+ Version: 0.1.0
4
+ Summary: LiveKit Agents plugin for tts-cache-router, a caching TTS router for Sarvam, Raya and ElevenLabs
5
+ Project-URL: Homepage, https://ttscacherouter.dev
6
+ Project-URL: Documentation, https://docs.ttscacherouter.dev/livekit
7
+ Project-URL: Source, https://github.com/talqing/tts-cache-router
8
+ Author: Oggnai Technologies Private Limited
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: ai,audio,cache,elevenlabs,livekit,raya,realtime,sarvam,tts,voice
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Topic :: Multimedia :: Sound/Audio
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.10.0
20
+ Requires-Dist: livekit-agents>=1.8.5
21
+ Description-Content-Type: text/markdown
22
+
23
+ # livekit-plugins-tts-cache-router
24
+
25
+ [LiveKit Agents](https://github.com/livekit/agents) plugin for
26
+ [tts-cache-router](https://ttscacherouter.dev): Sarvam, Raya and ElevenLabs text-to-speech,
27
+ with every sentence your agent has said before served from a per-account cache.
28
+
29
+ Same output whether you call the provider directly or through the router: each sentence reaches
30
+ the provider verbatim with your exact settings, and a cache hit replays a real provider take for
31
+ that exact request.
32
+
33
+ Full documentation: [docs.ttscacherouter.dev/livekit](https://docs.ttscacherouter.dev/livekit).
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ pip install livekit-plugins-tts-cache-router
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ ```python
44
+ from livekit.plugins import tts_cache_router
45
+
46
+ tts = tts_cache_router.TTS(
47
+ provider=tts_cache_router.Sarvam(model="bulbul:v3", speaker="shubh", language="hi-IN"),
48
+ )
49
+ # or
50
+ tts = tts_cache_router.TTS(
51
+ provider=tts_cache_router.Raya(
52
+ model="standard", voice_id="d6a002d0-230c-49b1-a137-b8a7d564b1ae", language="hi"
53
+ ),
54
+ )
55
+ # or
56
+ tts = tts_cache_router.TTS(
57
+ provider=tts_cache_router.ElevenLabs(voice_id="JBFqnCBsd6RMkjVDRZzb", model="eleven_flash_v2_5"),
58
+ )
59
+
60
+ session = AgentSession(tts=tts, ...)
61
+ ```
62
+
63
+ Before the first request, store your Sarvam, Raya or ElevenLabs API key in the dashboard at
64
+ [ttscacherouter.dev](https://ttscacherouter.dev/dashboard/provider-keys). The router keeps it
65
+ encrypted and uses it only to call that provider for your requests.
66
+
67
+ Set `TTS_CACHE_ROUTER_API_KEY` to your router API key, from the same dashboard (or pass
68
+ `api_key=`).
69
+
70
+ ### `TTS(...)`
71
+
72
+ | Argument | Default | |
73
+ |---|---|---|
74
+ | `provider` | required | `Sarvam(...)`, `Raya(...)` or `ElevenLabs(...)` |
75
+ | `api_key` | `$TTS_CACHE_ROUTER_API_KEY` | router API key |
76
+ | `base_url` | `wss://api.ttscacherouter.dev` | set to your own router when self-hosting |
77
+ | `sample_rate` | `24000` | 8000, 16000, 22050 or 24000; ElevenLabs also 32000, 44100 or 48000 |
78
+
79
+ How long cached audio is kept is your org's retention setting, in the dashboard.
80
+
81
+ ### `Sarvam(...)`
82
+
83
+ `model` (`"bulbul:v3"` or `"bulbul:v4-flash"`), `speaker`, `language` (e.g. `"hi-IN"`),
84
+ `pace` (0.5–2.0, default 1.0), `temperature` (0.01–1.0, default 0.6), `dict_id`, and for
85
+ `bulbul:v4-flash` only: `pitch` (-0.5–0.5), `loudness` (0.1–2.5), `enable_preprocessing`;
86
+ `min_buffer_size` (30–200) and `max_chunk_length` (50–500; by default each sentence is
87
+ synthesized whole).
88
+
89
+ ### `Raya(...)`
90
+
91
+ `model` (`"standard"` or `"m1"`), `voice_id`, `language` (e.g. `"hi"`), `speed` (0.5–1.5,
92
+ default 1.0).
93
+
94
+ ### `ElevenLabs(...)`
95
+
96
+ The settings of ElevenLabs' own LiveKit plugin: `voice_id`, `model` (default
97
+ `"eleven_turbo_v2_5"`; `eleven_v3` and `eleven_v4` models go through ElevenLabs' text-to-dialogue
98
+ API), `language` (optional; `"en-US"` or `"english"` is sent as `"en"`, as ElevenLabs' plugin
99
+ sends it), `voice_settings` (`VoiceSettings(stability, similarity_boost,
100
+ style=None, speed=None, use_speaker_boost=None)`; the voice's stored settings when omitted),
101
+ `apply_text_normalization` (`"auto"`, `"on"` or `"off"`), `apply_language_text_normalization`,
102
+ `enable_ssml_parsing`, `enable_logging`, `pronunciation_dictionary_locators`
103
+ (`PronunciationDictionaryLocator(pronunciation_dictionary_id, version_id)`, up to 3),
104
+ `sync_alignment` (default `True`: word-level timed transcripts) and `preferred_alignment`
105
+ (`"normalized"` or `"original"`).
106
+
107
+ ### Changing settings mid-session
108
+
109
+ ```python
110
+ tts.update_options(speaker="priya", pace=1.1) # the current provider's settings, by name
111
+ tts.update_options(provider=tts_cache_router.Raya(...)) # or another provider
112
+ ```
113
+
114
+ Replies that start afterwards use the new settings.
115
+
116
+ ### Interruptions
117
+
118
+ When the agent is interrupted, the plugin cancels the router segment and keeps the connection open,
119
+ so the next reply starts on a warm connection.
120
+
121
+ ### Metrics
122
+
123
+ `TTSMetrics.characters_count` counts only characters the provider synthesized (and billed) for
124
+ the request; sentences served from the cache count zero. `provider` and `model` report the
125
+ underlying provider, so usage dashboards attribute cost correctly.
@@ -0,0 +1,10 @@
1
+ livekit/plugins/tts_cache_router/__init__.py,sha256=OXR7NELx9SxMuSISsys-N9IEeZghFx_zY1pF2m2q18U,1649
2
+ livekit/plugins/tts_cache_router/log.py,sha256=nEtTyiwCvYSGS3ZKwz7N_ASSuEAUqkiHmfBuVbJ0b-s,79
3
+ livekit/plugins/tts_cache_router/providers.py,sha256=2Ewqyf3tZe4xwMFnZm5wtQLBMhPhz5zIIO_D15AW_ZE,12523
4
+ livekit/plugins/tts_cache_router/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ livekit/plugins/tts_cache_router/tts.py,sha256=nqJHNYqWBZfh7_VPdVVZtdS21eb28Y4WlsXiOBCDuBk,20257
6
+ livekit/plugins/tts_cache_router/version.py,sha256=XM9ITzC_IaEPTFvYwLyNKIqN9OhcXUa2ZONCeDVWYLo,622
7
+ livekit_plugins_tts_cache_router-0.1.0.dist-info/METADATA,sha256=1EIsDPHJ-_CAiX6O0NFe3zgX_txmKibWwwY6U4tsG80,5105
8
+ livekit_plugins_tts_cache_router-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
9
+ livekit_plugins_tts_cache_router-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
10
+ livekit_plugins_tts_cache_router-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.