livekit-plugins-vaakini 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.
- livekit_plugins_vaakini-0.1.0/.gitignore +3 -0
- livekit_plugins_vaakini-0.1.0/CHANGELOG.md +7 -0
- livekit_plugins_vaakini-0.1.0/LICENSE +201 -0
- livekit_plugins_vaakini-0.1.0/PKG-INFO +111 -0
- livekit_plugins_vaakini-0.1.0/README.md +90 -0
- livekit_plugins_vaakini-0.1.0/livekit/plugins/vaakini/__init__.py +52 -0
- livekit_plugins_vaakini-0.1.0/livekit/plugins/vaakini/log.py +3 -0
- livekit_plugins_vaakini-0.1.0/livekit/plugins/vaakini/py.typed +0 -0
- livekit_plugins_vaakini-0.1.0/livekit/plugins/vaakini/tts.py +644 -0
- livekit_plugins_vaakini-0.1.0/livekit/plugins/vaakini/version.py +15 -0
- livekit_plugins_vaakini-0.1.0/pyproject.toml +47 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (2026-11-16)
|
|
4
|
+
|
|
5
|
+
- The first release: `vaakini.TTS(voice=..., language=...)` for `vaakini-tts-1`, streamed and with
|
|
6
|
+
`synthesize()`. The model's settings are keyword arguments: `normalize`, `temperature`, `top_k`,
|
|
7
|
+
`top_p` and `repetition_penalty`.
|
|
@@ -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.
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: livekit-plugins-vaakini
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: LiveKit Agents plugin for Vaakini (https://vaakini.com): text to speech in 12 Indian languages
|
|
5
|
+
Project-URL: Homepage, https://vaakini.com
|
|
6
|
+
Project-URL: Documentation, https://docs.vaakini.com/livekit
|
|
7
|
+
Author: Oggnai Technologies Private Limited
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: ai,audio,hindi,indian-languages,livekit,realtime,text-to-speech,tts,vaakini,voice
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Topic :: Multimedia :: Sound/Audio
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
18
|
+
Requires-Python: >=3.10.0
|
|
19
|
+
Requires-Dist: livekit-agents>=1.8.5
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# livekit-plugins-vaakini
|
|
23
|
+
|
|
24
|
+
[LiveKit Agents](https://github.com/livekit/agents) plugin for [Vaakini](https://vaakini.com):
|
|
25
|
+
text to speech in 12 Indian languages with one model, `vaakini-tts-1`.
|
|
26
|
+
|
|
27
|
+
Full documentation: [docs.vaakini.com/livekit](https://docs.vaakini.com/livekit).
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install livekit-plugins-vaakini
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from livekit.agents import AgentSession
|
|
39
|
+
from livekit.plugins import vaakini
|
|
40
|
+
|
|
41
|
+
session = AgentSession(
|
|
42
|
+
tts=vaakini.TTS(voice="Monika", language="hi"),
|
|
43
|
+
# ... stt, llm, vad
|
|
44
|
+
)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Set `VAAKINI_API_KEY` to your API key, from the dashboard at [vaakini.com](https://vaakini.com)
|
|
48
|
+
(or pass `api_key=`).
|
|
49
|
+
|
|
50
|
+
### `TTS(...)`
|
|
51
|
+
|
|
52
|
+
| Argument | Default | |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| `voice` | required | a Vaakini voice's name, in any case (`"Monika"`), or the id of one of your org's custom voices (`"cv_…"`); `GET /v1/voices` lists them |
|
|
55
|
+
| `language` | `None` | the language the text is in: `"as"`, `"bn"`, `"en"`, `"gu"`, `"hi"`, `"kn"`, `"ml"`, `"mr"`, `"or"`, `"pa"`, `"ta"` or `"te"`. Left out, the model picks it from each sentence's script |
|
|
56
|
+
| `model` | `"vaakini-tts-1"` | the model; this is the only one |
|
|
57
|
+
| `normalize` | `None` (on) | numbers, currency, dates, times, phone numbers, URLs and emails spoken as words; `False` turns it off |
|
|
58
|
+
| `temperature` | `None` | sampling temperature, 0.1 to 1.5: lower is steadier |
|
|
59
|
+
| `top_k` | `None` | sample from the k likeliest codes, 1 to 2048 |
|
|
60
|
+
| `top_p` | `None` | nucleus sampling, above 0 and at most 1 |
|
|
61
|
+
| `repetition_penalty` | `None` | penalty on recently repeated codes, 0 to 5 |
|
|
62
|
+
| `api_key` | `$VAAKINI_API_KEY` | your Vaakini API key |
|
|
63
|
+
| `base_url` | `wss://api.vaakini.com` | Vaakini's URL |
|
|
64
|
+
| `http_session` | the job's | an aiohttp session to connect with |
|
|
65
|
+
|
|
66
|
+
`normalize`, `temperature`, `top_k`, `top_p` and `repetition_penalty` are sent only when
|
|
67
|
+
given: left as `None`, the model's own default applies. The audio is 24000 Hz, 16-bit, mono.
|
|
68
|
+
|
|
69
|
+
Vaakini checks the settings: when the session starts, the plugin connects and a wrong setting is
|
|
70
|
+
logged as an error, and a reply with a wrong one fails with `APIStatusError` (`bad_request`, not
|
|
71
|
+
retryable).
|
|
72
|
+
|
|
73
|
+
### How a reply is spoken
|
|
74
|
+
|
|
75
|
+
The plugin streams a reply's text to Vaakini as the LLM writes it. Vaakini splits it into
|
|
76
|
+
sentences and speaks each as soon as it is complete, so the first audio follows the reply's first
|
|
77
|
+
sentence. Transcripts follow the audio a sentence at a time. `tts.synthesize(text)` speaks a text
|
|
78
|
+
you have in full, the same way.
|
|
79
|
+
|
|
80
|
+
### Changing settings mid-session
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
tts.update_options(voice="Bunty", temperature=0.6)
|
|
84
|
+
tts.update_options(temperature=None) # back to the model's default
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Replies that start afterwards use the new settings. A setting left out keeps its value; `None`
|
|
88
|
+
puts one back to the model's default.
|
|
89
|
+
|
|
90
|
+
### Connections
|
|
91
|
+
|
|
92
|
+
When an `AgentSession` starts, it calls `tts.prewarm()`: the plugin connects to Vaakini, which
|
|
93
|
+
readies the model for the current settings at once, so the first reply doesn't wait for either.
|
|
94
|
+
Idle connections stay open between replies, for up to about 30 minutes, and are replaced at once
|
|
95
|
+
when a server restarts.
|
|
96
|
+
|
|
97
|
+
### Interruptions
|
|
98
|
+
|
|
99
|
+
When the agent is interrupted, the plugin cancels the reply at Vaakini, which stops speaking it,
|
|
100
|
+
and keeps the connection open, so the next reply starts on a warm connection.
|
|
101
|
+
|
|
102
|
+
### Metrics
|
|
103
|
+
|
|
104
|
+
`TTSMetrics.characters_count` is the characters Vaakini spoke for the reply, which are the ones
|
|
105
|
+
it charges for: the reply's sentences, without the spaces between them. An interrupted reply
|
|
106
|
+
reports its metrics too (`TTSMetrics.cancelled` set), counting the sentences sent in full before
|
|
107
|
+
the interruption.
|
|
108
|
+
|
|
109
|
+
## License
|
|
110
|
+
|
|
111
|
+
Apache-2.0.
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# livekit-plugins-vaakini
|
|
2
|
+
|
|
3
|
+
[LiveKit Agents](https://github.com/livekit/agents) plugin for [Vaakini](https://vaakini.com):
|
|
4
|
+
text to speech in 12 Indian languages with one model, `vaakini-tts-1`.
|
|
5
|
+
|
|
6
|
+
Full documentation: [docs.vaakini.com/livekit](https://docs.vaakini.com/livekit).
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pip install livekit-plugins-vaakini
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
from livekit.agents import AgentSession
|
|
18
|
+
from livekit.plugins import vaakini
|
|
19
|
+
|
|
20
|
+
session = AgentSession(
|
|
21
|
+
tts=vaakini.TTS(voice="Monika", language="hi"),
|
|
22
|
+
# ... stt, llm, vad
|
|
23
|
+
)
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Set `VAAKINI_API_KEY` to your API key, from the dashboard at [vaakini.com](https://vaakini.com)
|
|
27
|
+
(or pass `api_key=`).
|
|
28
|
+
|
|
29
|
+
### `TTS(...)`
|
|
30
|
+
|
|
31
|
+
| Argument | Default | |
|
|
32
|
+
|---|---|---|
|
|
33
|
+
| `voice` | required | a Vaakini voice's name, in any case (`"Monika"`), or the id of one of your org's custom voices (`"cv_…"`); `GET /v1/voices` lists them |
|
|
34
|
+
| `language` | `None` | the language the text is in: `"as"`, `"bn"`, `"en"`, `"gu"`, `"hi"`, `"kn"`, `"ml"`, `"mr"`, `"or"`, `"pa"`, `"ta"` or `"te"`. Left out, the model picks it from each sentence's script |
|
|
35
|
+
| `model` | `"vaakini-tts-1"` | the model; this is the only one |
|
|
36
|
+
| `normalize` | `None` (on) | numbers, currency, dates, times, phone numbers, URLs and emails spoken as words; `False` turns it off |
|
|
37
|
+
| `temperature` | `None` | sampling temperature, 0.1 to 1.5: lower is steadier |
|
|
38
|
+
| `top_k` | `None` | sample from the k likeliest codes, 1 to 2048 |
|
|
39
|
+
| `top_p` | `None` | nucleus sampling, above 0 and at most 1 |
|
|
40
|
+
| `repetition_penalty` | `None` | penalty on recently repeated codes, 0 to 5 |
|
|
41
|
+
| `api_key` | `$VAAKINI_API_KEY` | your Vaakini API key |
|
|
42
|
+
| `base_url` | `wss://api.vaakini.com` | Vaakini's URL |
|
|
43
|
+
| `http_session` | the job's | an aiohttp session to connect with |
|
|
44
|
+
|
|
45
|
+
`normalize`, `temperature`, `top_k`, `top_p` and `repetition_penalty` are sent only when
|
|
46
|
+
given: left as `None`, the model's own default applies. The audio is 24000 Hz, 16-bit, mono.
|
|
47
|
+
|
|
48
|
+
Vaakini checks the settings: when the session starts, the plugin connects and a wrong setting is
|
|
49
|
+
logged as an error, and a reply with a wrong one fails with `APIStatusError` (`bad_request`, not
|
|
50
|
+
retryable).
|
|
51
|
+
|
|
52
|
+
### How a reply is spoken
|
|
53
|
+
|
|
54
|
+
The plugin streams a reply's text to Vaakini as the LLM writes it. Vaakini splits it into
|
|
55
|
+
sentences and speaks each as soon as it is complete, so the first audio follows the reply's first
|
|
56
|
+
sentence. Transcripts follow the audio a sentence at a time. `tts.synthesize(text)` speaks a text
|
|
57
|
+
you have in full, the same way.
|
|
58
|
+
|
|
59
|
+
### Changing settings mid-session
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
tts.update_options(voice="Bunty", temperature=0.6)
|
|
63
|
+
tts.update_options(temperature=None) # back to the model's default
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Replies that start afterwards use the new settings. A setting left out keeps its value; `None`
|
|
67
|
+
puts one back to the model's default.
|
|
68
|
+
|
|
69
|
+
### Connections
|
|
70
|
+
|
|
71
|
+
When an `AgentSession` starts, it calls `tts.prewarm()`: the plugin connects to Vaakini, which
|
|
72
|
+
readies the model for the current settings at once, so the first reply doesn't wait for either.
|
|
73
|
+
Idle connections stay open between replies, for up to about 30 minutes, and are replaced at once
|
|
74
|
+
when a server restarts.
|
|
75
|
+
|
|
76
|
+
### Interruptions
|
|
77
|
+
|
|
78
|
+
When the agent is interrupted, the plugin cancels the reply at Vaakini, which stops speaking it,
|
|
79
|
+
and keeps the connection open, so the next reply starts on a warm connection.
|
|
80
|
+
|
|
81
|
+
### Metrics
|
|
82
|
+
|
|
83
|
+
`TTSMetrics.characters_count` is the characters Vaakini spoke for the reply, which are the ones
|
|
84
|
+
it charges for: the reply's sentences, without the spaces between them. An interrupted reply
|
|
85
|
+
reports its metrics too (`TTSMetrics.cancelled` set), counting the sentences sent in full before
|
|
86
|
+
the interruption.
|
|
87
|
+
|
|
88
|
+
## License
|
|
89
|
+
|
|
90
|
+
Apache-2.0.
|
|
@@ -0,0 +1,52 @@
|
|
|
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
|
+
|
|
16
|
+
"""Vaakini plugin for LiveKit Agents.
|
|
17
|
+
|
|
18
|
+
Text to speech in 12 Indian languages with Vaakini's model, `vaakini-tts-1`.
|
|
19
|
+
|
|
20
|
+
See https://docs.vaakini.com/livekit.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from .tts import TTS, ChunkedStream, SynthesizeStream
|
|
24
|
+
from .version import __version__
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"TTS",
|
|
28
|
+
"ChunkedStream",
|
|
29
|
+
"SynthesizeStream",
|
|
30
|
+
"__version__",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
from livekit.agents import Plugin
|
|
34
|
+
|
|
35
|
+
from .log import logger
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class VaakiniPlugin(Plugin):
|
|
39
|
+
def __init__(self) -> None:
|
|
40
|
+
super().__init__(__name__, __version__, __package__, logger)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
Plugin.register_plugin(VaakiniPlugin())
|
|
44
|
+
|
|
45
|
+
# Cleanup docs of unexported modules
|
|
46
|
+
_module = dir()
|
|
47
|
+
NOT_IN_ALL = [m for m in _module if m not in __all__]
|
|
48
|
+
|
|
49
|
+
__pdoc__ = {}
|
|
50
|
+
|
|
51
|
+
for n in NOT_IN_ALL:
|
|
52
|
+
__pdoc__[n] = False
|
|
File without changes
|
|
@@ -0,0 +1,644 @@
|
|
|
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
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import asyncio
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import time
|
|
22
|
+
import weakref
|
|
23
|
+
from collections.abc import AsyncIterable
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
from typing import Any, cast
|
|
26
|
+
|
|
27
|
+
import aiohttp
|
|
28
|
+
from livekit.agents import (
|
|
29
|
+
APIConnectionError,
|
|
30
|
+
APIError,
|
|
31
|
+
APIStatusError,
|
|
32
|
+
APITimeoutError,
|
|
33
|
+
tts,
|
|
34
|
+
utils,
|
|
35
|
+
)
|
|
36
|
+
from livekit.agents.metrics import TTSMetrics
|
|
37
|
+
from livekit.agents.metrics.base import Metadata
|
|
38
|
+
from livekit.agents.types import (
|
|
39
|
+
DEFAULT_API_CONNECT_OPTIONS,
|
|
40
|
+
NOT_GIVEN,
|
|
41
|
+
APIConnectOptions,
|
|
42
|
+
NotGivenOr,
|
|
43
|
+
TimedString,
|
|
44
|
+
)
|
|
45
|
+
from livekit.agents.utils import is_given
|
|
46
|
+
|
|
47
|
+
from .log import logger
|
|
48
|
+
|
|
49
|
+
API_KEY_ENV = "VAAKINI_API_KEY"
|
|
50
|
+
|
|
51
|
+
_DEFAULT_URL = "wss://api.vaakini.com"
|
|
52
|
+
_DEFAULT_MODEL = "vaakini-tts-1"
|
|
53
|
+
_PROVIDER = "Vaakini"
|
|
54
|
+
|
|
55
|
+
# The model's one sample rate: 16-bit mono PCM at 24 kHz.
|
|
56
|
+
_SAMPLE_RATE = 24000
|
|
57
|
+
|
|
58
|
+
# Vaakini closes a connection that sends nothing for 30 minutes; a pooled connection is retired
|
|
59
|
+
# before that, counted from its last reply's start.
|
|
60
|
+
_MAX_SESSION_DURATION = 1700
|
|
61
|
+
|
|
62
|
+
# The close code of a server that is restarting. It closes its idle connections at once, while
|
|
63
|
+
# new ones already reach the servers that replace it.
|
|
64
|
+
_SERVICE_RESTART = 1012
|
|
65
|
+
|
|
66
|
+
# Once all of a reply's text is sent, how long Vaakini may send nothing before the plugin gives up
|
|
67
|
+
# on the connection. Vaakini ends a reply itself, with an error, when the model is late (within a
|
|
68
|
+
# few seconds), so this only catches a server that went silent.
|
|
69
|
+
_SILENCE_TIMEOUT_S = 30.0
|
|
70
|
+
|
|
71
|
+
# After an interruption, how long to wait for Vaakini to confirm the cancel before giving up on
|
|
72
|
+
# reusing the connection.
|
|
73
|
+
_CANCEL_TIMEOUT_S = 2.0
|
|
74
|
+
|
|
75
|
+
# Vaakini's error codes as HTTP statuses, the ones `POST /v1/audio/speech` answers them with.
|
|
76
|
+
_STATUS_FOR_CODE = {
|
|
77
|
+
"bad_request": 400,
|
|
78
|
+
"unauthorized": 401,
|
|
79
|
+
"insufficient_credits": 402,
|
|
80
|
+
"rate_limited": 429,
|
|
81
|
+
"unavailable": 502,
|
|
82
|
+
"timeout": 504,
|
|
83
|
+
"internal": 500,
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# What Vaakini's API answers a `/v1/stream` handshake it refuses, by status.
|
|
88
|
+
_HANDSHAKE_REFUSALS = {
|
|
89
|
+
401: "missing or invalid API key",
|
|
90
|
+
402: "this org is out of credit: buy credit in the dashboard (Billing)",
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass(frozen=True)
|
|
95
|
+
class _Settings:
|
|
96
|
+
"""The model, voice and settings, in the names of Vaakini's API. Vaakini validates them; only
|
|
97
|
+
their shape is checked here."""
|
|
98
|
+
|
|
99
|
+
model: str
|
|
100
|
+
voice: str
|
|
101
|
+
language: str | None
|
|
102
|
+
# The model's options. None: not sent, so the model's default applies.
|
|
103
|
+
normalize: bool | None
|
|
104
|
+
temperature: float | None
|
|
105
|
+
top_k: int | None
|
|
106
|
+
top_p: float | None
|
|
107
|
+
repetition_penalty: float | None
|
|
108
|
+
|
|
109
|
+
def __post_init__(self) -> None:
|
|
110
|
+
if not self.voice:
|
|
111
|
+
raise ValueError(
|
|
112
|
+
"voice is required: a Vaakini voice's name, e.g. \"Monika\", or a custom voice's id"
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
def start_fields(self) -> dict[str, Any]:
|
|
116
|
+
options = {
|
|
117
|
+
"normalize": self.normalize,
|
|
118
|
+
"temperature": self.temperature,
|
|
119
|
+
"top_k": self.top_k,
|
|
120
|
+
"top_p": self.top_p,
|
|
121
|
+
"repetition_penalty": self.repetition_penalty,
|
|
122
|
+
}
|
|
123
|
+
fields: dict[str, Any] = {
|
|
124
|
+
"model": self.model,
|
|
125
|
+
"voice": self.voice,
|
|
126
|
+
"sample_rate": _SAMPLE_RATE,
|
|
127
|
+
"format": "pcm",
|
|
128
|
+
"options": {name: value for name, value in options.items() if value is not None},
|
|
129
|
+
}
|
|
130
|
+
if self.language is not None:
|
|
131
|
+
fields["language"] = self.language
|
|
132
|
+
return fields
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class TTS(tts.TTS):
|
|
136
|
+
def __init__(
|
|
137
|
+
self,
|
|
138
|
+
*,
|
|
139
|
+
voice: str,
|
|
140
|
+
language: str | None = None,
|
|
141
|
+
model: str = _DEFAULT_MODEL,
|
|
142
|
+
normalize: bool | None = None,
|
|
143
|
+
temperature: float | None = None,
|
|
144
|
+
top_k: int | None = None,
|
|
145
|
+
top_p: float | None = None,
|
|
146
|
+
repetition_penalty: float | None = None,
|
|
147
|
+
api_key: str | None = None,
|
|
148
|
+
base_url: str | None = None,
|
|
149
|
+
http_session: aiohttp.ClientSession | None = None,
|
|
150
|
+
) -> None:
|
|
151
|
+
"""Text-to-speech with Vaakini.
|
|
152
|
+
|
|
153
|
+
A reply's text is streamed to Vaakini as the LLM writes it. Vaakini splits it into
|
|
154
|
+
sentences and speaks each as soon as it is complete, so the first audio follows the
|
|
155
|
+
reply's first sentence.
|
|
156
|
+
|
|
157
|
+
Vaakini checks the settings: when the agent session starts (a wrong one is logged then),
|
|
158
|
+
and again when each reply starts.
|
|
159
|
+
|
|
160
|
+
Args:
|
|
161
|
+
voice: The voice: a Vaakini voice's name, in any case (``"Monika"``), or the id of one
|
|
162
|
+
of your org's custom voices (``"cv_…"``). ``GET /v1/voices`` lists them.
|
|
163
|
+
language: The language the text is in, one of ``"as"``, ``"bn"``, ``"en"``, ``"gu"``,
|
|
164
|
+
``"hi"``, ``"kn"``, ``"ml"``, ``"mr"``, ``"or"``, ``"pa"``, ``"ta"`` and ``"te"``.
|
|
165
|
+
Left out, the model picks it from each sentence's script.
|
|
166
|
+
model: The model. ``"vaakini-tts-1"``, the default, is the only one.
|
|
167
|
+
normalize: Speak numbers, currency, dates, times, phone numbers, URLs and emails as
|
|
168
|
+
words in the reply's language. On unless set to False.
|
|
169
|
+
temperature: Sampling temperature, 0.1 to 1.5: lower is steadier.
|
|
170
|
+
top_k: Sample from the k likeliest codes, 1 to 2048.
|
|
171
|
+
top_p: Nucleus sampling, above 0 and at most 1.
|
|
172
|
+
repetition_penalty: Penalty on recently repeated codes, 0 to 5. Each of these five
|
|
173
|
+
is sent only when given: left as ``None``, the model's own default applies.
|
|
174
|
+
api_key: Vaakini API key. Defaults to the ``VAAKINI_API_KEY`` environment variable.
|
|
175
|
+
base_url: Vaakini's URL. Defaults to ``wss://api.vaakini.com``.
|
|
176
|
+
http_session: Optional aiohttp session; defaults to the job's.
|
|
177
|
+
"""
|
|
178
|
+
super().__init__(
|
|
179
|
+
capabilities=tts.TTSCapabilities(streaming=True, aligned_transcript=True),
|
|
180
|
+
sample_rate=_SAMPLE_RATE,
|
|
181
|
+
num_channels=1,
|
|
182
|
+
)
|
|
183
|
+
key = api_key or os.environ.get(API_KEY_ENV)
|
|
184
|
+
if not key:
|
|
185
|
+
raise ValueError(f"Vaakini API key is required, either as api_key or set {API_KEY_ENV}")
|
|
186
|
+
self._settings = _Settings(
|
|
187
|
+
model=model,
|
|
188
|
+
voice=voice,
|
|
189
|
+
language=language,
|
|
190
|
+
normalize=normalize,
|
|
191
|
+
temperature=temperature,
|
|
192
|
+
top_k=top_k,
|
|
193
|
+
top_p=top_p,
|
|
194
|
+
repetition_penalty=repetition_penalty,
|
|
195
|
+
)
|
|
196
|
+
self._api_key = key
|
|
197
|
+
url = base_url.rstrip("/") if base_url is not None else _DEFAULT_URL
|
|
198
|
+
self._url = f"{url}/v1/stream"
|
|
199
|
+
self._session = http_session
|
|
200
|
+
self._pool = utils.ConnectionPool[aiohttp.ClientWebSocketResponse](
|
|
201
|
+
connect_cb=self._connect_ws,
|
|
202
|
+
close_cb=self._close_ws,
|
|
203
|
+
max_session_duration=_MAX_SESSION_DURATION,
|
|
204
|
+
mark_refreshed_on_get=True,
|
|
205
|
+
)
|
|
206
|
+
self._streams = weakref.WeakSet[SynthesizeStream]()
|
|
207
|
+
self._background: set[asyncio.Task[Any]] = set()
|
|
208
|
+
# A reader per pooled connection while it waits for its next segment.
|
|
209
|
+
self._idle_readers: dict[aiohttp.ClientWebSocketResponse, asyncio.Task[None]] = {}
|
|
210
|
+
|
|
211
|
+
def update_options(
|
|
212
|
+
self,
|
|
213
|
+
*,
|
|
214
|
+
voice: NotGivenOr[str] = NOT_GIVEN,
|
|
215
|
+
language: NotGivenOr[str | None] = NOT_GIVEN,
|
|
216
|
+
model: NotGivenOr[str] = NOT_GIVEN,
|
|
217
|
+
normalize: NotGivenOr[bool | None] = NOT_GIVEN,
|
|
218
|
+
temperature: NotGivenOr[float | None] = NOT_GIVEN,
|
|
219
|
+
top_k: NotGivenOr[int | None] = NOT_GIVEN,
|
|
220
|
+
top_p: NotGivenOr[float | None] = NOT_GIVEN,
|
|
221
|
+
repetition_penalty: NotGivenOr[float | None] = NOT_GIVEN,
|
|
222
|
+
) -> None:
|
|
223
|
+
"""Change the settings. Replies that start from now on use them. A setting left out
|
|
224
|
+
keeps its value.
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
voice: The voice's name, or a custom voice's id.
|
|
228
|
+
language: The language code; ``None`` leaves it to the model.
|
|
229
|
+
model: The model.
|
|
230
|
+
normalize: As in the constructor; ``None`` goes back to the model's default.
|
|
231
|
+
temperature: As in the constructor; ``None`` goes back to the model's default.
|
|
232
|
+
top_k: As in the constructor; ``None`` goes back to the model's default.
|
|
233
|
+
top_p: As in the constructor; ``None`` goes back to the model's default.
|
|
234
|
+
repetition_penalty: As in the constructor; ``None`` goes back to the model's default.
|
|
235
|
+
"""
|
|
236
|
+
current = self._settings
|
|
237
|
+
self._settings = _Settings(
|
|
238
|
+
model=model if is_given(model) else current.model,
|
|
239
|
+
voice=voice if is_given(voice) else current.voice,
|
|
240
|
+
language=language if is_given(language) else current.language,
|
|
241
|
+
normalize=normalize if is_given(normalize) else current.normalize,
|
|
242
|
+
temperature=temperature if is_given(temperature) else current.temperature,
|
|
243
|
+
top_k=top_k if is_given(top_k) else current.top_k,
|
|
244
|
+
top_p=top_p if is_given(top_p) else current.top_p,
|
|
245
|
+
repetition_penalty=(
|
|
246
|
+
repetition_penalty if is_given(repetition_penalty) else current.repetition_penalty
|
|
247
|
+
),
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
@property
|
|
251
|
+
def model(self) -> str:
|
|
252
|
+
return self._settings.model
|
|
253
|
+
|
|
254
|
+
@property
|
|
255
|
+
def provider(self) -> str:
|
|
256
|
+
return _PROVIDER
|
|
257
|
+
|
|
258
|
+
def _ensure_session(self) -> aiohttp.ClientSession:
|
|
259
|
+
if not self._session:
|
|
260
|
+
self._session = utils.http_context.http_session()
|
|
261
|
+
return self._session
|
|
262
|
+
|
|
263
|
+
async def _connect_ws(self, timeout: float) -> aiohttp.ClientWebSocketResponse:
|
|
264
|
+
async def connect() -> aiohttp.ClientWebSocketResponse:
|
|
265
|
+
ws = await self._ensure_session().ws_connect(
|
|
266
|
+
self._url, headers={"Authorization": f"Bearer {self._api_key}"}
|
|
267
|
+
)
|
|
268
|
+
# aiohttp types text frames per `decode_text`; this module reads them as str.
|
|
269
|
+
return cast(aiohttp.ClientWebSocketResponse, ws)
|
|
270
|
+
|
|
271
|
+
try:
|
|
272
|
+
ws = await asyncio.wait_for(connect(), timeout)
|
|
273
|
+
except asyncio.TimeoutError:
|
|
274
|
+
raise APITimeoutError("timed out connecting to Vaakini") from None
|
|
275
|
+
except aiohttp.WSServerHandshakeError as e:
|
|
276
|
+
# aiohttp keeps a refused handshake's status but not its body, so Vaakini's own
|
|
277
|
+
# message can't be read here: the status is reported, with what Vaakini's API means
|
|
278
|
+
# by it where it documents one.
|
|
279
|
+
meaning = _HANDSHAKE_REFUSALS.get(e.status)
|
|
280
|
+
raise APIStatusError(
|
|
281
|
+
f"Vaakini refused the connection: HTTP {e.status}"
|
|
282
|
+
+ (f" ({meaning})" if meaning else ""),
|
|
283
|
+
status_code=e.status,
|
|
284
|
+
) from None
|
|
285
|
+
except Exception as e:
|
|
286
|
+
raise APIConnectionError(f"connecting to Vaakini failed: {type(e).__name__}") from None
|
|
287
|
+
# Vaakini readies the model for these settings now, so the first reply (on a prewarmed
|
|
288
|
+
# connection, often seconds later) doesn't wait for it.
|
|
289
|
+
try:
|
|
290
|
+
await ws.send_str(json.dumps(self._warm_message(self._settings)))
|
|
291
|
+
except (aiohttp.ClientError, ConnectionError) as e:
|
|
292
|
+
await ws.close()
|
|
293
|
+
raise APIConnectionError(f"connecting to Vaakini failed: {type(e).__name__}") from None
|
|
294
|
+
self._watch_idle(ws)
|
|
295
|
+
return ws
|
|
296
|
+
|
|
297
|
+
async def _close_ws(self, ws: aiohttp.ClientWebSocketResponse) -> None:
|
|
298
|
+
await self._unwatch_idle(ws)
|
|
299
|
+
await ws.close()
|
|
300
|
+
|
|
301
|
+
def _watch_idle(self, ws: aiohttp.ClientWebSocketResponse) -> None:
|
|
302
|
+
self._idle_readers[ws] = asyncio.create_task(self._read_idle(ws))
|
|
303
|
+
|
|
304
|
+
async def _unwatch_idle(self, ws: aiohttp.ClientWebSocketResponse) -> None:
|
|
305
|
+
task = self._idle_readers.pop(ws, None)
|
|
306
|
+
if task is not None:
|
|
307
|
+
await utils.aio.gracefully_cancel(task)
|
|
308
|
+
|
|
309
|
+
async def _read_idle(self, ws: aiohttp.ClientWebSocketResponse) -> None:
|
|
310
|
+
"""Reads a pooled connection while it waits for its next segment, so Vaakini's pings are
|
|
311
|
+
answered (aiohttp answers them only while the socket is read) and a connection Vaakini
|
|
312
|
+
closed (its idle timeout, a restart) leaves the pool at once rather than failing the next
|
|
313
|
+
segment; one a restart closed is replaced at once. Vaakini sends nothing else to an idle
|
|
314
|
+
connection, so anything that arrives (its close, or an error) ends the connection."""
|
|
315
|
+
msg = await ws.receive()
|
|
316
|
+
if msg.type == aiohttp.WSMsgType.TEXT:
|
|
317
|
+
data = json.loads(msg.data)
|
|
318
|
+
if data["type"] == "error":
|
|
319
|
+
# Vaakini refused the `warm` this connection opened with (a voice the org can't
|
|
320
|
+
# speak, an option out of range) and closes it. `prewarm()` has nobody to raise
|
|
321
|
+
# to, so it is logged; a reply with these settings asks again on a connection of
|
|
322
|
+
# its own and fails with this same error, which is not retried.
|
|
323
|
+
logger.error(f"Vaakini refused the TTS settings: {data['code']}: {data['message']}")
|
|
324
|
+
else:
|
|
325
|
+
logger.warning(
|
|
326
|
+
"Vaakini sent a message to an idle connection", extra={"type": data["type"]}
|
|
327
|
+
)
|
|
328
|
+
self._idle_readers.pop(ws, None)
|
|
329
|
+
self._pool.remove(ws)
|
|
330
|
+
self._in_background(ws.close())
|
|
331
|
+
if ws.close_code == _SERVICE_RESTART:
|
|
332
|
+
# Reconnect now, so the next reply finds a warm connection on a new server instead of
|
|
333
|
+
# paying for the connect itself.
|
|
334
|
+
self._pool.prewarm()
|
|
335
|
+
|
|
336
|
+
def _give_back(self, ws: aiohttp.ClientWebSocketResponse) -> None:
|
|
337
|
+
self._watch_idle(ws)
|
|
338
|
+
self._pool.put(ws)
|
|
339
|
+
|
|
340
|
+
def _in_background(self, coro: Any) -> None:
|
|
341
|
+
task = asyncio.create_task(coro)
|
|
342
|
+
self._background.add(task)
|
|
343
|
+
task.add_done_callback(self._background.discard)
|
|
344
|
+
|
|
345
|
+
def _discard(self, ws: aiohttp.ClientWebSocketResponse) -> None:
|
|
346
|
+
# Closing promptly tells Vaakini the client is gone, so it stops sending audio nobody will
|
|
347
|
+
# play. The pool would otherwise close it only on its next use.
|
|
348
|
+
self._pool.remove(ws)
|
|
349
|
+
self._in_background(self._close_ws(ws))
|
|
350
|
+
|
|
351
|
+
async def _cancel_segment(
|
|
352
|
+
self,
|
|
353
|
+
ws: aiohttp.ClientWebSocketResponse,
|
|
354
|
+
segment_id: str,
|
|
355
|
+
report: Any,
|
|
356
|
+
) -> None:
|
|
357
|
+
"""Barge-in: stop the segment but keep the connection warm for the next turn. Audio still
|
|
358
|
+
in flight for the segment is discarded until Vaakini confirms the cancel.
|
|
359
|
+
|
|
360
|
+
`report(counts, cancelled=...)` reports the segment's counts: those of `cancelled` (the
|
|
361
|
+
sentences sent in full before the cancel), or of `done` when the segment finished before
|
|
362
|
+
Vaakini saw the cancel (its `cancelled` then has zeros)."""
|
|
363
|
+
|
|
364
|
+
async def confirmed() -> None:
|
|
365
|
+
await ws.send_str(json.dumps({"type": "cancel", "segment_id": segment_id}))
|
|
366
|
+
finished = False
|
|
367
|
+
while True:
|
|
368
|
+
msg = await ws.receive()
|
|
369
|
+
if msg.type == aiohttp.WSMsgType.BINARY:
|
|
370
|
+
continue
|
|
371
|
+
if msg.type != aiohttp.WSMsgType.TEXT:
|
|
372
|
+
raise ConnectionError("Vaakini closed the connection")
|
|
373
|
+
data = json.loads(msg.data)
|
|
374
|
+
if data["type"] == "done" and data["segment_id"] == segment_id:
|
|
375
|
+
finished = True
|
|
376
|
+
report(data, cancelled=False)
|
|
377
|
+
elif data["type"] == "cancelled" and data["segment_id"] == segment_id:
|
|
378
|
+
if not finished:
|
|
379
|
+
report(data, cancelled=True)
|
|
380
|
+
return
|
|
381
|
+
elif data["type"] == "error":
|
|
382
|
+
raise ConnectionError(f"Vaakini error {data['code']}")
|
|
383
|
+
|
|
384
|
+
try:
|
|
385
|
+
await asyncio.wait_for(confirmed(), _CANCEL_TIMEOUT_S)
|
|
386
|
+
except Exception as e:
|
|
387
|
+
logger.debug(
|
|
388
|
+
"could not reuse the connection after a cancel",
|
|
389
|
+
extra={"error": type(e).__name__},
|
|
390
|
+
)
|
|
391
|
+
self._discard(ws)
|
|
392
|
+
return
|
|
393
|
+
self._give_back(ws)
|
|
394
|
+
|
|
395
|
+
def prewarm(self) -> None:
|
|
396
|
+
self._pool.prewarm()
|
|
397
|
+
|
|
398
|
+
def synthesize(
|
|
399
|
+
self,
|
|
400
|
+
text: str,
|
|
401
|
+
*,
|
|
402
|
+
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
|
|
403
|
+
) -> ChunkedStream:
|
|
404
|
+
return ChunkedStream(tts=self, input_text=text, conn_options=conn_options)
|
|
405
|
+
|
|
406
|
+
def stream(
|
|
407
|
+
self, *, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS
|
|
408
|
+
) -> SynthesizeStream:
|
|
409
|
+
stream = SynthesizeStream(tts=self, conn_options=conn_options)
|
|
410
|
+
self._streams.add(stream)
|
|
411
|
+
return stream
|
|
412
|
+
|
|
413
|
+
async def aclose(self) -> None:
|
|
414
|
+
for stream in list(self._streams):
|
|
415
|
+
await stream.aclose()
|
|
416
|
+
self._streams.clear()
|
|
417
|
+
await utils.aio.gracefully_cancel(*self._background)
|
|
418
|
+
await self._pool.aclose()
|
|
419
|
+
|
|
420
|
+
def _start_message(self, segment_id: str, settings: _Settings) -> dict[str, Any]:
|
|
421
|
+
return {"type": "start", "segment_id": segment_id, **settings.start_fields()}
|
|
422
|
+
|
|
423
|
+
def _warm_message(self, settings: _Settings) -> dict[str, Any]:
|
|
424
|
+
return {"type": "warm", **settings.start_fields()}
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _api_error(data: dict[str, Any]) -> APIError:
|
|
428
|
+
return APIStatusError(
|
|
429
|
+
f"Vaakini {data['code']}: {data['message']}",
|
|
430
|
+
status_code=_STATUS_FOR_CODE.get(data["code"], 500),
|
|
431
|
+
body=data,
|
|
432
|
+
retryable=bool(data["retryable"]),
|
|
433
|
+
)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _initialize(output_emitter: tts.AudioEmitter, *, streamed: bool) -> str:
|
|
437
|
+
"""Returns the request id."""
|
|
438
|
+
request_id = utils.shortuuid()
|
|
439
|
+
output_emitter.initialize(
|
|
440
|
+
request_id=request_id,
|
|
441
|
+
sample_rate=_SAMPLE_RATE,
|
|
442
|
+
num_channels=1,
|
|
443
|
+
mime_type="audio/pcm",
|
|
444
|
+
stream=streamed,
|
|
445
|
+
)
|
|
446
|
+
return request_id
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
async def _run_segment(
|
|
450
|
+
stream: SynthesizeStream | ChunkedStream,
|
|
451
|
+
output_emitter: tts.AudioEmitter,
|
|
452
|
+
*,
|
|
453
|
+
request_id: str,
|
|
454
|
+
send_input: Any,
|
|
455
|
+
streamed: bool,
|
|
456
|
+
) -> None:
|
|
457
|
+
"""One segment: `start`, text, `flush`, then audio until `done`.
|
|
458
|
+
|
|
459
|
+
`send_input(ws, segment_id, first_text_at)` sends the `text` messages and the `flush`.
|
|
460
|
+
"""
|
|
461
|
+
vaakini_tts: TTS = stream._tts
|
|
462
|
+
conn_options = stream._conn_options
|
|
463
|
+
segment_id = utils.shortuuid()
|
|
464
|
+
# The settings as of the segment's start: update_options applies from the next segment.
|
|
465
|
+
settings = vaakini_tts._settings
|
|
466
|
+
if streamed:
|
|
467
|
+
output_emitter.start_segment(segment_id=segment_id)
|
|
468
|
+
|
|
469
|
+
started = time.perf_counter()
|
|
470
|
+
first_text_at: list[float] = []
|
|
471
|
+
first_audio_at: float | None = None
|
|
472
|
+
pushed_bytes = 0
|
|
473
|
+
done: dict[str, Any] | None = None
|
|
474
|
+
|
|
475
|
+
async def sender(ws: aiohttp.ClientWebSocketResponse) -> None:
|
|
476
|
+
await ws.send_str(json.dumps(vaakini_tts._start_message(segment_id, settings)))
|
|
477
|
+
await send_input(ws, segment_id, first_text_at)
|
|
478
|
+
|
|
479
|
+
def report(counts: dict[str, Any], *, cancelled: bool) -> None:
|
|
480
|
+
"""Metrics from `done`'s or `cancelled`'s counts: the characters Vaakini spoke, which are
|
|
481
|
+
the ones it charges for."""
|
|
482
|
+
ttfb = first_audio_at - first_text_at[0] if first_audio_at and first_text_at else -1.0
|
|
483
|
+
vaakini_tts.emit(
|
|
484
|
+
"metrics_collected",
|
|
485
|
+
TTSMetrics(
|
|
486
|
+
timestamp=time.time(),
|
|
487
|
+
request_id=request_id,
|
|
488
|
+
segment_id=segment_id if streamed else None,
|
|
489
|
+
ttfb=ttfb,
|
|
490
|
+
duration=time.perf_counter() - started,
|
|
491
|
+
characters_count=counts["characters"],
|
|
492
|
+
audio_duration=pushed_bytes / 2 / _SAMPLE_RATE,
|
|
493
|
+
cancelled=cancelled,
|
|
494
|
+
label=vaakini_tts.label,
|
|
495
|
+
streamed=streamed,
|
|
496
|
+
acquire_time=stream._acquire_time,
|
|
497
|
+
connection_reused=stream._connection_reused,
|
|
498
|
+
metadata=Metadata(model_name=settings.model, model_provider=_PROVIDER),
|
|
499
|
+
),
|
|
500
|
+
)
|
|
501
|
+
|
|
502
|
+
pool = vaakini_tts._pool
|
|
503
|
+
try:
|
|
504
|
+
ws = await pool.get(timeout=conn_options.timeout)
|
|
505
|
+
except APIError:
|
|
506
|
+
raise
|
|
507
|
+
except Exception as e:
|
|
508
|
+
raise APIConnectionError(f"connecting to Vaakini failed: {type(e).__name__}") from e
|
|
509
|
+
stream._acquire_time = pool.last_acquire_time
|
|
510
|
+
stream._connection_reused = pool.last_connection_reused
|
|
511
|
+
# The segment reads the connection from here on.
|
|
512
|
+
await vaakini_tts._unwatch_idle(ws)
|
|
513
|
+
send_task = asyncio.create_task(sender(ws))
|
|
514
|
+
try:
|
|
515
|
+
while done is None:
|
|
516
|
+
try:
|
|
517
|
+
msg = await ws.receive(timeout=_SILENCE_TIMEOUT_S)
|
|
518
|
+
except asyncio.TimeoutError:
|
|
519
|
+
# Until all input is sent, silence just means the LLM is still talking.
|
|
520
|
+
if send_task.done():
|
|
521
|
+
send_task.result()
|
|
522
|
+
raise APITimeoutError("Vaakini sent nothing in time") from None
|
|
523
|
+
continue
|
|
524
|
+
|
|
525
|
+
if msg.type == aiohttp.WSMsgType.BINARY:
|
|
526
|
+
if first_audio_at is None:
|
|
527
|
+
first_audio_at = time.perf_counter()
|
|
528
|
+
pushed_bytes += len(msg.data)
|
|
529
|
+
output_emitter.push(msg.data)
|
|
530
|
+
continue
|
|
531
|
+
if msg.type != aiohttp.WSMsgType.TEXT:
|
|
532
|
+
raise APIConnectionError("Vaakini closed the connection")
|
|
533
|
+
|
|
534
|
+
data = json.loads(msg.data)
|
|
535
|
+
if data["type"] == "sentence":
|
|
536
|
+
# Transcripts stay in step with speech at sentence granularity.
|
|
537
|
+
output_emitter.push_timed_transcript(
|
|
538
|
+
TimedString(text=data["text"] + " ", start_time=pushed_bytes / 2 / _SAMPLE_RATE)
|
|
539
|
+
)
|
|
540
|
+
elif data["type"] == "done":
|
|
541
|
+
done = data
|
|
542
|
+
elif data["type"] == "error":
|
|
543
|
+
raise _api_error(data)
|
|
544
|
+
else:
|
|
545
|
+
logger.warning("unexpected Vaakini message", extra={"type": data["type"]})
|
|
546
|
+
send_task.result()
|
|
547
|
+
except asyncio.CancelledError:
|
|
548
|
+
# Barge-in. The `start` may already be out, so ask Vaakini to cancel the segment (a no-op
|
|
549
|
+
# it still confirms if the segment never started or already finished), and return the
|
|
550
|
+
# warm connection to the pool once it confirms.
|
|
551
|
+
await utils.aio.gracefully_cancel(send_task)
|
|
552
|
+
vaakini_tts._in_background(vaakini_tts._cancel_segment(ws, segment_id, report))
|
|
553
|
+
raise
|
|
554
|
+
except APIError:
|
|
555
|
+
vaakini_tts._discard(ws)
|
|
556
|
+
raise
|
|
557
|
+
except Exception as e:
|
|
558
|
+
vaakini_tts._discard(ws)
|
|
559
|
+
raise APIConnectionError(f"Vaakini connection failed: {type(e).__name__}") from e
|
|
560
|
+
finally:
|
|
561
|
+
await utils.aio.gracefully_cancel(send_task)
|
|
562
|
+
vaakini_tts._give_back(ws)
|
|
563
|
+
|
|
564
|
+
if streamed:
|
|
565
|
+
output_emitter.end_segment()
|
|
566
|
+
else:
|
|
567
|
+
output_emitter.flush()
|
|
568
|
+
|
|
569
|
+
assert done is not None, "the receive loop ends only at `done`"
|
|
570
|
+
report(done, cancelled=False)
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
class ChunkedStream(tts.ChunkedStream):
|
|
574
|
+
def __init__(self, *, tts: TTS, input_text: str, conn_options: APIConnectOptions) -> None:
|
|
575
|
+
super().__init__(tts=tts, input_text=input_text, conn_options=conn_options)
|
|
576
|
+
self._tts: TTS = tts
|
|
577
|
+
|
|
578
|
+
# Overrides a private method (verified on livekit-agents 1.8.5 and 1.8.12): the base class
|
|
579
|
+
# reports the characters of the text it was given, and nothing for an interrupted reply.
|
|
580
|
+
# _run_segment emits the metrics with the characters Vaakini counted instead.
|
|
581
|
+
async def _metrics_monitor_task(self, event_aiter: AsyncIterable[tts.SynthesizedAudio]) -> None:
|
|
582
|
+
async for _ in event_aiter:
|
|
583
|
+
pass
|
|
584
|
+
|
|
585
|
+
async def _run(self, output_emitter: tts.AudioEmitter) -> None:
|
|
586
|
+
async def send_input(
|
|
587
|
+
ws: aiohttp.ClientWebSocketResponse,
|
|
588
|
+
segment_id: str,
|
|
589
|
+
first_text_at: list[float],
|
|
590
|
+
) -> None:
|
|
591
|
+
if self._input_text:
|
|
592
|
+
first_text_at.append(time.perf_counter())
|
|
593
|
+
await ws.send_str(
|
|
594
|
+
json.dumps(
|
|
595
|
+
{
|
|
596
|
+
"type": "text",
|
|
597
|
+
"segment_id": segment_id,
|
|
598
|
+
"text": self._input_text,
|
|
599
|
+
}
|
|
600
|
+
)
|
|
601
|
+
)
|
|
602
|
+
await ws.send_str(json.dumps({"type": "flush", "segment_id": segment_id}))
|
|
603
|
+
|
|
604
|
+
request_id = _initialize(output_emitter, streamed=False)
|
|
605
|
+
await _run_segment(
|
|
606
|
+
self, output_emitter, request_id=request_id, send_input=send_input, streamed=False
|
|
607
|
+
)
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
class SynthesizeStream(tts.SynthesizeStream):
|
|
611
|
+
def __init__(self, *, tts: TTS, conn_options: APIConnectOptions) -> None:
|
|
612
|
+
super().__init__(tts=tts, conn_options=conn_options)
|
|
613
|
+
self._tts: TTS = tts
|
|
614
|
+
|
|
615
|
+
# Overrides a private method (verified on livekit-agents 1.8.5 and 1.8.12): the base class
|
|
616
|
+
# reports the characters of the text it was given, and nothing for an interrupted reply.
|
|
617
|
+
# _run_segment emits the metrics with the characters Vaakini counted instead.
|
|
618
|
+
async def _metrics_monitor_task(self, event_aiter: AsyncIterable[tts.SynthesizedAudio]) -> None:
|
|
619
|
+
async for _ in event_aiter:
|
|
620
|
+
pass
|
|
621
|
+
|
|
622
|
+
async def _run(self, output_emitter: tts.AudioEmitter) -> None:
|
|
623
|
+
async def send_input(
|
|
624
|
+
ws: aiohttp.ClientWebSocketResponse,
|
|
625
|
+
segment_id: str,
|
|
626
|
+
first_text_at: list[float],
|
|
627
|
+
) -> None:
|
|
628
|
+
# One stream is one segment: livekit-agents passes on no text after the first flush
|
|
629
|
+
# (one SynthesizeStream per segment).
|
|
630
|
+
async for data in self._input_ch:
|
|
631
|
+
if isinstance(data, self._FlushSentinel):
|
|
632
|
+
break
|
|
633
|
+
if not first_text_at:
|
|
634
|
+
first_text_at.append(time.perf_counter())
|
|
635
|
+
self._mark_started()
|
|
636
|
+
await ws.send_str(
|
|
637
|
+
json.dumps({"type": "text", "segment_id": segment_id, "text": data})
|
|
638
|
+
)
|
|
639
|
+
await ws.send_str(json.dumps({"type": "flush", "segment_id": segment_id}))
|
|
640
|
+
|
|
641
|
+
request_id = _initialize(output_emitter, streamed=True)
|
|
642
|
+
await _run_segment(
|
|
643
|
+
self, output_emitter, request_id=request_id, send_input=send_input, streamed=True
|
|
644
|
+
)
|
|
@@ -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,47 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "livekit-plugins-vaakini"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "LiveKit Agents plugin for Vaakini (https://vaakini.com): text to speech in 12 Indian languages"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
requires-python = ">=3.10.0"
|
|
12
|
+
authors = [{ name = "Oggnai Technologies Private Limited" }]
|
|
13
|
+
keywords = [
|
|
14
|
+
"voice",
|
|
15
|
+
"ai",
|
|
16
|
+
"realtime",
|
|
17
|
+
"audio",
|
|
18
|
+
"livekit",
|
|
19
|
+
"tts",
|
|
20
|
+
"text-to-speech",
|
|
21
|
+
"vaakini",
|
|
22
|
+
"hindi",
|
|
23
|
+
"indian-languages",
|
|
24
|
+
]
|
|
25
|
+
classifiers = [
|
|
26
|
+
"Intended Audience :: Developers",
|
|
27
|
+
"License :: OSI Approved :: Apache Software License",
|
|
28
|
+
"Topic :: Multimedia :: Sound/Audio",
|
|
29
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
30
|
+
"Programming Language :: Python :: 3",
|
|
31
|
+
"Programming Language :: Python :: 3.10",
|
|
32
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
33
|
+
]
|
|
34
|
+
dependencies = ["livekit-agents>=1.8.5"]
|
|
35
|
+
|
|
36
|
+
[project.urls]
|
|
37
|
+
Homepage = "https://vaakini.com"
|
|
38
|
+
Documentation = "https://docs.vaakini.com/livekit"
|
|
39
|
+
|
|
40
|
+
[tool.hatch.version]
|
|
41
|
+
path = "livekit/plugins/vaakini/version.py"
|
|
42
|
+
|
|
43
|
+
[tool.hatch.build.targets.wheel]
|
|
44
|
+
packages = ["livekit"]
|
|
45
|
+
|
|
46
|
+
[tool.hatch.build.targets.sdist]
|
|
47
|
+
include = ["/livekit", "/CHANGELOG.md"]
|