tw-livekit 0.1.0__tar.gz

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.

Potentially problematic release.


This version of tw-livekit might be problematic. Click here for more details.

@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TeenageWorks
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.4
2
+ Name: tw-livekit
3
+ Version: 0.1.0
4
+ Summary: TeenageWorks Blue streaming TTS for LiveKit Agents
5
+ Author: TeenageWorks
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: livekit-agents==1.8.1
11
+ Requires-Dist: websockets==15.0.1
12
+ Dynamic: license-file
13
+
14
+ # TW LiveKit
15
+
16
+ Streaming TeenageWorks Blue TTS for LiveKit Agents.
17
+
18
+ ```bash
19
+ pip install tw-livekit
20
+ ```
21
+
22
+ ```python
23
+ from livekit.agents import AgentSession
24
+ from tw_livekit import BlueTTS
25
+
26
+ tts = BlueTTS(voice="Amelia", language="hinglish", normalization=True)
27
+ session = AgentSession(stt=your_stt, llm=your_llm, vad=your_vad, tts=tts)
28
+ ```
29
+
30
+ Replace `your_stt`, `your_llm` and `your_vad` with your existing providers. Set the main Blue key in the server-side environment variable `BLUE_TTS_API_KEY`. Credentials must never be sent to the browser.
31
+
32
+ Voices: Bunty, Pari M, Amelia, Brittney. Languages: `en`, `hi`, `hinglish`. PCM: 48 kHz, mono, signed 16-bit. Normalization defaults ON; generated leading quiet is retained. Each synthesis uses a fresh authenticated WebSocket; cancellation closes it and partial speech is never automatically replayed. The adapter emits 20 ms audio frames and verifies each complete Blue segment's byte count, SHA-256 and natural stop, followed by `done` and normal WebSocket closure.
33
+
34
+ LiveKit streams LLM text into `stream()`. Eligible punctuation releases Blue phrases; explicit LiveKit flush/end markers release pending text. Long input is flushed at whitespace when possible, before Blue's 1,000-character pending buffer is exceeded. The adapter sends text and receives audio concurrently. All clients share the endpoint's connection limit; the adapter does not reserve idle connections.
35
+
36
+ ```python
37
+ @tts.on("metrics_collected")
38
+ def on_metrics(m):
39
+ print({"first_pcm_ms": m.ttfb * 1000,
40
+ "setup_ms": m.acquire_time * 1000,
41
+ "cancelled": m.cancelled})
42
+ ```
43
+
44
+ Streaming TTS timing starts when the first text is sent, after connection/configuration; `setup_ms` is separate. The `synthesize()` whole-text path uses LiveKit's elapsed request timing, including setup. Neither is listener-side audible onset or total conversational response latency. Leading quiet, STT endpointing, LLM generation and transport/playout contribute separately.
45
+
46
+ Requires Python 3.11+, LiveKit Agents 1.8.1 and websockets 15.0.1. On systems whose Python build lacks the OS trust-store path, set `SSL_CERT_FILE` to your system CA bundle; retain certificate verification.
47
+
48
+ The distribution name is `tw-livekit`; the Python import is `tw_livekit`. Only this integration is included: no model weights, inference service source, private credentials or fleet tooling.
@@ -0,0 +1,35 @@
1
+ # TW LiveKit
2
+
3
+ Streaming TeenageWorks Blue TTS for LiveKit Agents.
4
+
5
+ ```bash
6
+ pip install tw-livekit
7
+ ```
8
+
9
+ ```python
10
+ from livekit.agents import AgentSession
11
+ from tw_livekit import BlueTTS
12
+
13
+ tts = BlueTTS(voice="Amelia", language="hinglish", normalization=True)
14
+ session = AgentSession(stt=your_stt, llm=your_llm, vad=your_vad, tts=tts)
15
+ ```
16
+
17
+ Replace `your_stt`, `your_llm` and `your_vad` with your existing providers. Set the main Blue key in the server-side environment variable `BLUE_TTS_API_KEY`. Credentials must never be sent to the browser.
18
+
19
+ Voices: Bunty, Pari M, Amelia, Brittney. Languages: `en`, `hi`, `hinglish`. PCM: 48 kHz, mono, signed 16-bit. Normalization defaults ON; generated leading quiet is retained. Each synthesis uses a fresh authenticated WebSocket; cancellation closes it and partial speech is never automatically replayed. The adapter emits 20 ms audio frames and verifies each complete Blue segment's byte count, SHA-256 and natural stop, followed by `done` and normal WebSocket closure.
20
+
21
+ LiveKit streams LLM text into `stream()`. Eligible punctuation releases Blue phrases; explicit LiveKit flush/end markers release pending text. Long input is flushed at whitespace when possible, before Blue's 1,000-character pending buffer is exceeded. The adapter sends text and receives audio concurrently. All clients share the endpoint's connection limit; the adapter does not reserve idle connections.
22
+
23
+ ```python
24
+ @tts.on("metrics_collected")
25
+ def on_metrics(m):
26
+ print({"first_pcm_ms": m.ttfb * 1000,
27
+ "setup_ms": m.acquire_time * 1000,
28
+ "cancelled": m.cancelled})
29
+ ```
30
+
31
+ Streaming TTS timing starts when the first text is sent, after connection/configuration; `setup_ms` is separate. The `synthesize()` whole-text path uses LiveKit's elapsed request timing, including setup. Neither is listener-side audible onset or total conversational response latency. Leading quiet, STT endpointing, LLM generation and transport/playout contribute separately.
32
+
33
+ Requires Python 3.11+, LiveKit Agents 1.8.1 and websockets 15.0.1. On systems whose Python build lacks the OS trust-store path, set `SSL_CERT_FILE` to your system CA bundle; retain certificate verification.
34
+
35
+ The distribution name is `tw-livekit`; the Python import is `tw_livekit`. Only this integration is included: no model weights, inference service source, private credentials or fleet tooling.
@@ -0,0 +1,16 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tw-livekit"
7
+ version = "0.1.0"
8
+ description = "TeenageWorks Blue streaming TTS for LiveKit Agents"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ authors = [{name = "TeenageWorks"}]
13
+ dependencies = ["livekit-agents==1.8.1", "websockets==15.0.1"]
14
+
15
+ [tool.setuptools.packages.find]
16
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ from .tts import BlueTTS
2
+
3
+ __all__ = ["BlueTTS"]
@@ -0,0 +1,242 @@
1
+ import asyncio
2
+ import hashlib
3
+ import json
4
+ import os
5
+ import ssl
6
+ import time
7
+ import uuid
8
+
9
+ from livekit.agents import (
10
+ APIConnectOptions,
11
+ APIError,
12
+ DEFAULT_API_CONNECT_OPTIONS,
13
+ tts,
14
+ )
15
+ from websockets.asyncio.client import connect
16
+
17
+
18
+ URL = 'wss://bluemachines.clarifyed.ai/v1/tts/ws'
19
+ VOICES = {
20
+ 'Bunty': 'voice_407baf0b8d207300bdfd326aef6cacb9',
21
+ 'Pari M': 'voice_47814eb3b3984421949ce9a5169fd901',
22
+ 'Amelia': 'voice_bfc22e10bc1b493089f57bc4f0103d9f',
23
+ 'Brittney': 'voice_d873dea37b254c1a95310eaa1db30f7d',
24
+ }
25
+
26
+
27
+ class _BlueConnect(connect):
28
+ def process_redirect(self, exc):
29
+ return exc
30
+
31
+
32
+ class BlueTTS(tts.TTS):
33
+ def __init__(
34
+ self, *, voice='Amelia', language='hinglish', normalization=True, api_key=None,
35
+ ):
36
+ key = api_key if api_key is not None else os.environ.get('BLUE_TTS_API_KEY', '')
37
+ key = key.strip()
38
+ if not key or any(ord(c) <= 32 or ord(c) >= 127 for c in key):
39
+ raise ValueError('Set BLUE_TTS_API_KEY to the main Blue API key')
40
+ if voice not in VOICES or language not in ('en', 'hi', 'hinglish'):
41
+ raise ValueError('Unsupported voice or language')
42
+ if type(normalization) is not bool:
43
+ raise ValueError('normalization must be boolean')
44
+ super().__init__(
45
+ capabilities=tts.TTSCapabilities(streaming=True),
46
+ sample_rate=48000, num_channels=1,
47
+ )
48
+ self._blue_key = key
49
+ self._blue_voice = VOICES[voice]
50
+ self._blue_language = language
51
+ self._blue_normalization = normalization
52
+
53
+ @property
54
+ def model(self):
55
+ return 'teen-v1-blue'
56
+
57
+ @property
58
+ def provider(self):
59
+ return 'TeenageWorks Blue'
60
+
61
+ def stream(self, *, conn_options=DEFAULT_API_CONNECT_OPTIONS):
62
+ options = APIConnectOptions(max_retry=0, timeout=conn_options.timeout)
63
+ return _BlueStream(tts=self, conn_options=options)
64
+
65
+ def synthesize(self, text, *, conn_options=DEFAULT_API_CONNECT_OPTIONS):
66
+ options = APIConnectOptions(max_retry=0, timeout=conn_options.timeout)
67
+ return _BlueChunkedStream(tts=self, input_text=text, conn_options=options)
68
+
69
+
70
+ class _BlueChunkedStream(tts.ChunkedStream):
71
+ async def _run(self, output_emitter):
72
+ output_emitter.initialize(
73
+ request_id=uuid.uuid4().hex, sample_rate=48000, num_channels=1,
74
+ mime_type='audio/pcm', frame_size_ms=20,
75
+ )
76
+ async with _BlueStream(
77
+ tts=self._tts, conn_options=self._conn_options, emit_metrics=False,
78
+ ) as stream:
79
+ stream.push_text(self._input_text)
80
+ stream.end_input()
81
+ async for event in stream:
82
+ self._acquire_time = stream._acquire_time
83
+ output_emitter.push(event.frame.data.tobytes())
84
+
85
+
86
+ class _BlueStream(tts.SynthesizeStream):
87
+ def __init__(self, *, tts, conn_options, emit_metrics=True):
88
+ self._emit_blue_metrics = emit_metrics
89
+ super().__init__(tts=tts, conn_options=conn_options)
90
+
91
+ async def _metrics_monitor_task(self, event_aiter):
92
+ if self._emit_blue_metrics:
93
+ await super()._metrics_monitor_task(event_aiter)
94
+ else:
95
+ async for event in event_aiter:
96
+ pass
97
+
98
+ async def _run(self, output_emitter):
99
+ request_id = uuid.uuid4().hex
100
+ output_emitter.initialize(
101
+ request_id=request_id, sample_rate=48000, num_channels=1,
102
+ mime_type='audio/pcm', frame_size_ms=20, stream=True,
103
+ )
104
+ output_emitter.start_segment(segment_id=request_id)
105
+ acquire_started = time.perf_counter()
106
+ tls = ssl.create_default_context()
107
+ tls.minimum_version = ssl.TLSVersion.TLSv1_2
108
+ sender = receiver = input_done_wait = None
109
+ input_done = asyncio.Event()
110
+ meaningful = False
111
+
112
+ async def event(ws):
113
+ raw = await asyncio.wait_for(ws.recv(), self._conn_options.timeout)
114
+ return raw if isinstance(raw, bytes) else json.loads(raw)
115
+
116
+ try:
117
+ async with _BlueConnect(
118
+ URL, ssl=tls,
119
+ additional_headers={'Authorization': 'Bearer ' + self._tts._blue_key},
120
+ origin=None, compression=None, proxy=None,
121
+ open_timeout=self._conn_options.timeout, close_timeout=5,
122
+ max_size=2**20, max_queue=4,
123
+ ) as ws:
124
+ ready = await event(ws)
125
+ if (not isinstance(ready, dict) or ready.get('type') != 'ready'
126
+ or (ready.get('format'), ready.get('sample_rate'), ready.get('channels'))
127
+ != ('s16le', 48000, 1)
128
+ or self._tts._blue_voice not in ready['voices'].values()):
129
+ raise RuntimeError('Unexpected Blue ready event')
130
+ await ws.send(json.dumps({
131
+ 'type': 'configure', 'voice': self._tts._blue_voice,
132
+ 'language': self._tts._blue_language, 'reset': True,
133
+ 'normalization': self._tts._blue_normalization,
134
+ }))
135
+ configured = await event(ws)
136
+ if (not isinstance(configured, dict) or configured.get('type') != 'configured'
137
+ or configured.get('voice') != self._tts._blue_voice
138
+ or configured.get('normalization') is not self._tts._blue_normalization):
139
+ raise RuntimeError('Blue configuration refused')
140
+ self._acquire_time = time.perf_counter() - acquire_started
141
+
142
+ async def send():
143
+ nonlocal meaningful
144
+ pending_chars = 0
145
+ async for value in self._input_ch:
146
+ if isinstance(value, self._FlushSentinel):
147
+ if pending_chars:
148
+ await ws.send('{"type":"flush"}')
149
+ pending_chars = 0
150
+ else:
151
+ meaningful = meaningful or bool(value.strip())
152
+ offset = 0
153
+ while offset < len(value):
154
+ room = 1000 - pending_chars
155
+ fragment = value[offset:offset + min(256, room)]
156
+ should_flush = False
157
+ if pending_chars + len(fragment) >= 750:
158
+ cut = max((i + 1 for i, c in enumerate(fragment)
159
+ if c.isspace()), default=0)
160
+ if cut:
161
+ fragment = fragment[:cut]
162
+ should_flush = True
163
+ self._mark_started()
164
+ await ws.send(json.dumps({
165
+ 'type': 'text', 'text': fragment,
166
+ }, ensure_ascii=False))
167
+ offset += len(fragment)
168
+ pending_chars += len(fragment)
169
+ if should_flush or pending_chars == 1000:
170
+ await ws.send('{"type":"flush"}')
171
+ pending_chars = 0
172
+ await ws.send('{"type":"finish"}')
173
+ input_done.set()
174
+
175
+ async def next_response():
176
+ if input_done.is_set():
177
+ return await event(ws)
178
+ read = asyncio.create_task(ws.recv())
179
+ try:
180
+ await asyncio.wait((read, input_done_wait),
181
+ return_when=asyncio.FIRST_COMPLETED)
182
+ if not read.done():
183
+ raw = await asyncio.wait_for(read, self._conn_options.timeout)
184
+ else:
185
+ raw = read.result()
186
+ return raw if isinstance(raw, bytes) else json.loads(raw)
187
+ finally:
188
+ read.cancel()
189
+ await asyncio.gather(read, return_exceptions=True)
190
+
191
+ async def receive():
192
+ current = None
193
+ seen = set()
194
+ completed = 0
195
+ while True:
196
+ value = await next_response()
197
+ if isinstance(value, bytes):
198
+ if current is None or len(value) % 2:
199
+ raise RuntimeError('Unexpected Blue PCM')
200
+ current['hash'].update(value)
201
+ current['bytes'] += len(value)
202
+ output_emitter.push(value)
203
+ elif value.get('type') == 'segment_start':
204
+ if current is not None or value['id'] in seen:
205
+ raise RuntimeError('Unexpected Blue segment ordering')
206
+ seen.add(value['id'])
207
+ current = {'id': value['id'], 'bytes': 0, 'hash': hashlib.sha256()}
208
+ elif value.get('type') == 'segment_done':
209
+ if (current is None or current['id'] != value['id']
210
+ or not current['bytes'] or current['bytes'] != value['bytes']
211
+ or current['hash'].hexdigest() != value['sha256']
212
+ or value.get('natural_stop') is not True):
213
+ raise RuntimeError('Blue PCM integrity or native-stop failure')
214
+ current = None
215
+ completed += 1
216
+ elif value.get('type') == 'done':
217
+ if current is not None or (meaningful and not completed):
218
+ raise RuntimeError('Incomplete Blue stream')
219
+ await asyncio.wait_for(ws.wait_closed(), self._conn_options.timeout)
220
+ if ws.close_code != 1000:
221
+ raise RuntimeError('Abnormal Blue WebSocket close')
222
+ output_emitter.end_segment()
223
+ return
224
+ elif value.get('type') == 'error':
225
+ raise RuntimeError('Blue server error: ' + str(value.get('code')))
226
+ else:
227
+ raise RuntimeError('Unexpected Blue event')
228
+
229
+ input_done_wait = asyncio.create_task(input_done.wait())
230
+ sender = asyncio.create_task(send())
231
+ receiver = asyncio.create_task(receive())
232
+ try:
233
+ await asyncio.gather(sender, receiver)
234
+ finally:
235
+ for task in (sender, receiver, input_done_wait):
236
+ task.cancel()
237
+ await asyncio.gather(sender, receiver, input_done_wait, return_exceptions=True)
238
+ except asyncio.CancelledError:
239
+ raise
240
+ except Exception as error:
241
+ message = str(error).replace(self._tts._blue_key, '[REDACTED]')
242
+ raise APIError('Blue WebSocket TTS failed: ' + message, retryable=False) from None
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.4
2
+ Name: tw-livekit
3
+ Version: 0.1.0
4
+ Summary: TeenageWorks Blue streaming TTS for LiveKit Agents
5
+ Author: TeenageWorks
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: livekit-agents==1.8.1
11
+ Requires-Dist: websockets==15.0.1
12
+ Dynamic: license-file
13
+
14
+ # TW LiveKit
15
+
16
+ Streaming TeenageWorks Blue TTS for LiveKit Agents.
17
+
18
+ ```bash
19
+ pip install tw-livekit
20
+ ```
21
+
22
+ ```python
23
+ from livekit.agents import AgentSession
24
+ from tw_livekit import BlueTTS
25
+
26
+ tts = BlueTTS(voice="Amelia", language="hinglish", normalization=True)
27
+ session = AgentSession(stt=your_stt, llm=your_llm, vad=your_vad, tts=tts)
28
+ ```
29
+
30
+ Replace `your_stt`, `your_llm` and `your_vad` with your existing providers. Set the main Blue key in the server-side environment variable `BLUE_TTS_API_KEY`. Credentials must never be sent to the browser.
31
+
32
+ Voices: Bunty, Pari M, Amelia, Brittney. Languages: `en`, `hi`, `hinglish`. PCM: 48 kHz, mono, signed 16-bit. Normalization defaults ON; generated leading quiet is retained. Each synthesis uses a fresh authenticated WebSocket; cancellation closes it and partial speech is never automatically replayed. The adapter emits 20 ms audio frames and verifies each complete Blue segment's byte count, SHA-256 and natural stop, followed by `done` and normal WebSocket closure.
33
+
34
+ LiveKit streams LLM text into `stream()`. Eligible punctuation releases Blue phrases; explicit LiveKit flush/end markers release pending text. Long input is flushed at whitespace when possible, before Blue's 1,000-character pending buffer is exceeded. The adapter sends text and receives audio concurrently. All clients share the endpoint's connection limit; the adapter does not reserve idle connections.
35
+
36
+ ```python
37
+ @tts.on("metrics_collected")
38
+ def on_metrics(m):
39
+ print({"first_pcm_ms": m.ttfb * 1000,
40
+ "setup_ms": m.acquire_time * 1000,
41
+ "cancelled": m.cancelled})
42
+ ```
43
+
44
+ Streaming TTS timing starts when the first text is sent, after connection/configuration; `setup_ms` is separate. The `synthesize()` whole-text path uses LiveKit's elapsed request timing, including setup. Neither is listener-side audible onset or total conversational response latency. Leading quiet, STT endpointing, LLM generation and transport/playout contribute separately.
45
+
46
+ Requires Python 3.11+, LiveKit Agents 1.8.1 and websockets 15.0.1. On systems whose Python build lacks the OS trust-store path, set `SSL_CERT_FILE` to your system CA bundle; retain certificate verification.
47
+
48
+ The distribution name is `tw-livekit`; the Python import is `tw_livekit`. Only this integration is included: no model weights, inference service source, private credentials or fleet tooling.
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/tw_livekit/__init__.py
5
+ src/tw_livekit/tts.py
6
+ src/tw_livekit.egg-info/PKG-INFO
7
+ src/tw_livekit.egg-info/SOURCES.txt
8
+ src/tw_livekit.egg-info/dependency_links.txt
9
+ src/tw_livekit.egg-info/requires.txt
10
+ src/tw_livekit.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ livekit-agents==1.8.1
2
+ websockets==15.0.1
@@ -0,0 +1 @@
1
+ tw_livekit