pipecat-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.
@@ -0,0 +1,3 @@
1
+ .venv/
2
+ __pycache__/
3
+ dist/
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-16)
4
+
5
+ - The first release: `VaakiniTTSService` and `VaakiniTTSSettings` for `vaakini-tts-1`. The model's
6
+ settings are fields of `VaakiniTTSSettings`: `normalize`, `temperature`, `top_k`, `top_p` and
7
+ `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,123 @@
1
+ Metadata-Version: 2.5
2
+ Name: pipecat-vaakini
3
+ Version: 0.1.0
4
+ Summary: Pipecat TTS service 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/pipecat
7
+ Author: Oggnai Technologies Private Limited
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: ai,audio,hindi,indian-languages,pipecat,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.11
16
+ Classifier: Topic :: Multimedia :: Sound/Audio
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.11
19
+ Requires-Dist: pipecat-ai>=1.12.0
20
+ Description-Content-Type: text/markdown
21
+
22
+ # pipecat-vaakini
23
+
24
+ [Pipecat](https://github.com/pipecat-ai/pipecat) TTS service 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/pipecat](https://docs.vaakini.com/pipecat).
28
+
29
+ Tested with Pipecat v1.12.0 and v1.16.0. Maintained by Oggnai Technologies, the company that runs
30
+ Vaakini.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ pip install pipecat-vaakini
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ```python
41
+ import os
42
+
43
+ from pipecat_vaakini import VaakiniTTSService
44
+
45
+ tts = VaakiniTTSService(
46
+ api_key=os.environ["VAAKINI_API_KEY"],
47
+ settings=VaakiniTTSService.Settings(voice="Monika", language="hi"),
48
+ )
49
+
50
+ pipeline = Pipeline(
51
+ [transport.input(), stt, user_aggregator, llm, tts, transport.output(), assistant_aggregator]
52
+ )
53
+ ```
54
+
55
+ Your API key is in the dashboard at [vaakini.com](https://vaakini.com).
56
+
57
+ ### `VaakiniTTSService(...)`
58
+
59
+ | Argument | Default | |
60
+ |---|---|---|
61
+ | `api_key` | required | your Vaakini API key |
62
+ | `settings` | required | `VaakiniTTSService.Settings(...)`, below |
63
+ | `base_url` | `wss://api.vaakini.com` | Vaakini's URL |
64
+
65
+ Other keyword arguments go to Pipecat's `WebsocketTTSService`, except `text_aggregation_mode`
66
+ (Vaakini splits the text into sentences itself, so the service streams the LLM's text to it as it
67
+ arrives) and `sample_rate`: the audio is 24000 Hz, and the pipeline's output transport resamples it
68
+ to its own rate.
69
+
70
+ ### `VaakiniTTSService.Settings(...)`
71
+
72
+ | Setting | Default | |
73
+ |---|---|---|
74
+ | `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 |
75
+ | `language` | `None` | the language the text is in: `"as"`, `"bn"`, `"en"`, `"gu"`, `"hi"`, `"kn"`, `"ml"`, `"mr"`, `"or"`, `"pa"`, `"ta"` or `"te"`, or its Pipecat `Language` (`Language.HI`; a region, as in `Language.HI_IN`, is dropped). Left out, the model picks it from each sentence's script |
76
+ | `model` | `"vaakini-tts-1"` | the model; this is the only one |
77
+ | `normalize` | `None` (on) | numbers, currency, dates, times, phone numbers, URLs and emails spoken as words; `False` turns it off |
78
+ | `temperature` | `None` | sampling temperature, 0.1 to 1.5: lower is steadier |
79
+ | `top_k` | `None` | sample from the k likeliest codes, 1 to 2048 |
80
+ | `top_p` | `None` | nucleus sampling, above 0 and at most 1 |
81
+ | `repetition_penalty` | `None` | penalty on recently repeated codes, 0 to 5 |
82
+
83
+ `normalize`, `temperature`, `top_k`, `top_p` and `repetition_penalty` are sent only when
84
+ set: left out or `None`, the model's own default applies.
85
+
86
+ Vaakini checks the settings: a wrong one is reported as an `ErrorFrame`.
87
+
88
+ ### How a reply is spoken
89
+
90
+ The service streams the LLM's text to Vaakini as it arrives. Vaakini splits it into sentences and
91
+ speaks each as soon as it is complete, so the first audio follows the reply's first sentence.
92
+
93
+ ### Changing settings mid-session
94
+
95
+ ```python
96
+ from pipecat.frames.frames import TTSUpdateSettingsFrame
97
+
98
+ await worker.queue_frame(
99
+ TTSUpdateSettingsFrame(delta=VaakiniTTSService.Settings(voice="Bunty", temperature=0.6))
100
+ )
101
+ ```
102
+
103
+ Replies that start afterwards use the new settings. A setting left out of the update keeps its
104
+ value; `None` puts one back to the model's default (`Settings(temperature=None)`).
105
+
106
+ ### Interruptions
107
+
108
+ When the user interrupts, the service tells Vaakini to stop the reply. The next reply starts on
109
+ the same connection.
110
+
111
+ ### Transcripts
112
+
113
+ The service's `TTSTextFrame`s follow the audio: each sentence's words as its audio starts.
114
+
115
+ ### Metrics
116
+
117
+ With usage metrics on, each reply's `TTSUsageMetricsData` is the characters Vaakini spoke, which
118
+ are the ones it charges for: the reply's sentences, without the spaces between them. An
119
+ interrupted reply counts the sentences sent in full before the interruption.
120
+
121
+ ## License
122
+
123
+ Apache-2.0.
@@ -0,0 +1,102 @@
1
+ # pipecat-vaakini
2
+
3
+ [Pipecat](https://github.com/pipecat-ai/pipecat) TTS service 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/pipecat](https://docs.vaakini.com/pipecat).
7
+
8
+ Tested with Pipecat v1.12.0 and v1.16.0. Maintained by Oggnai Technologies, the company that runs
9
+ Vaakini.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install pipecat-vaakini
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```python
20
+ import os
21
+
22
+ from pipecat_vaakini import VaakiniTTSService
23
+
24
+ tts = VaakiniTTSService(
25
+ api_key=os.environ["VAAKINI_API_KEY"],
26
+ settings=VaakiniTTSService.Settings(voice="Monika", language="hi"),
27
+ )
28
+
29
+ pipeline = Pipeline(
30
+ [transport.input(), stt, user_aggregator, llm, tts, transport.output(), assistant_aggregator]
31
+ )
32
+ ```
33
+
34
+ Your API key is in the dashboard at [vaakini.com](https://vaakini.com).
35
+
36
+ ### `VaakiniTTSService(...)`
37
+
38
+ | Argument | Default | |
39
+ |---|---|---|
40
+ | `api_key` | required | your Vaakini API key |
41
+ | `settings` | required | `VaakiniTTSService.Settings(...)`, below |
42
+ | `base_url` | `wss://api.vaakini.com` | Vaakini's URL |
43
+
44
+ Other keyword arguments go to Pipecat's `WebsocketTTSService`, except `text_aggregation_mode`
45
+ (Vaakini splits the text into sentences itself, so the service streams the LLM's text to it as it
46
+ arrives) and `sample_rate`: the audio is 24000 Hz, and the pipeline's output transport resamples it
47
+ to its own rate.
48
+
49
+ ### `VaakiniTTSService.Settings(...)`
50
+
51
+ | Setting | Default | |
52
+ |---|---|---|
53
+ | `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 |
54
+ | `language` | `None` | the language the text is in: `"as"`, `"bn"`, `"en"`, `"gu"`, `"hi"`, `"kn"`, `"ml"`, `"mr"`, `"or"`, `"pa"`, `"ta"` or `"te"`, or its Pipecat `Language` (`Language.HI`; a region, as in `Language.HI_IN`, is dropped). Left out, the model picks it from each sentence's script |
55
+ | `model` | `"vaakini-tts-1"` | the model; this is the only one |
56
+ | `normalize` | `None` (on) | numbers, currency, dates, times, phone numbers, URLs and emails spoken as words; `False` turns it off |
57
+ | `temperature` | `None` | sampling temperature, 0.1 to 1.5: lower is steadier |
58
+ | `top_k` | `None` | sample from the k likeliest codes, 1 to 2048 |
59
+ | `top_p` | `None` | nucleus sampling, above 0 and at most 1 |
60
+ | `repetition_penalty` | `None` | penalty on recently repeated codes, 0 to 5 |
61
+
62
+ `normalize`, `temperature`, `top_k`, `top_p` and `repetition_penalty` are sent only when
63
+ set: left out or `None`, the model's own default applies.
64
+
65
+ Vaakini checks the settings: a wrong one is reported as an `ErrorFrame`.
66
+
67
+ ### How a reply is spoken
68
+
69
+ The service streams the LLM's text to Vaakini as it arrives. Vaakini splits it into sentences and
70
+ speaks each as soon as it is complete, so the first audio follows the reply's first sentence.
71
+
72
+ ### Changing settings mid-session
73
+
74
+ ```python
75
+ from pipecat.frames.frames import TTSUpdateSettingsFrame
76
+
77
+ await worker.queue_frame(
78
+ TTSUpdateSettingsFrame(delta=VaakiniTTSService.Settings(voice="Bunty", temperature=0.6))
79
+ )
80
+ ```
81
+
82
+ Replies that start afterwards use the new settings. A setting left out of the update keeps its
83
+ value; `None` puts one back to the model's default (`Settings(temperature=None)`).
84
+
85
+ ### Interruptions
86
+
87
+ When the user interrupts, the service tells Vaakini to stop the reply. The next reply starts on
88
+ the same connection.
89
+
90
+ ### Transcripts
91
+
92
+ The service's `TTSTextFrame`s follow the audio: each sentence's words as its audio starts.
93
+
94
+ ### Metrics
95
+
96
+ With usage metrics on, each reply's `TTSUsageMetricsData` is the characters Vaakini spoke, which
97
+ are the ones it charges for: the reply's sentences, without the spaces between them. An
98
+ interrupted reply counts the sentences sent in full before the interruption.
99
+
100
+ ## License
101
+
102
+ Apache-2.0.
@@ -0,0 +1,30 @@
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 text-to-speech for Pipecat.
17
+
18
+ Text to speech in 12 Indian languages with Vaakini's model, `vaakini-tts-1`.
19
+
20
+ See https://docs.vaakini.com/pipecat.
21
+ """
22
+
23
+ from .tts import VaakiniTTSService, VaakiniTTSSettings
24
+ from .version import __version__
25
+
26
+ __all__ = [
27
+ "VaakiniTTSService",
28
+ "VaakiniTTSSettings",
29
+ "__version__",
30
+ ]
File without changes
@@ -0,0 +1,746 @@
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 text-to-speech service for Pipecat."""
17
+
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import json
22
+ import time
23
+ from collections import deque
24
+ from collections.abc import AsyncGenerator
25
+ from dataclasses import dataclass, field
26
+ from typing import Any
27
+
28
+ from loguru import logger
29
+ from pipecat.frames.frames import (
30
+ Frame,
31
+ MetricsFrame,
32
+ StartFrame,
33
+ TTSAudioRawFrame,
34
+ TTSStoppedFrame,
35
+ )
36
+ from pipecat.metrics.metrics import TTSUsageMetricsData
37
+ from pipecat.processors.metrics.frame_processor_metrics import FrameProcessorMetrics
38
+ from pipecat.services.settings import TTSSettings
39
+ from pipecat.services.tts_service import TextAggregationMode, WebsocketTTSService
40
+ from pipecat.transcriptions.language import Language
41
+ from pipecat.utils.errors import ErrorCategory, classify_http_status_code
42
+ from pipecat.utils.tracing.service_decorators import traced_tts
43
+ from pipecat.utils.types import NOT_GIVEN, NotGiven, is_given
44
+ from websockets.exceptions import ConnectionClosed, ConnectionClosedOK, InvalidStatus
45
+ from websockets.protocol import State
46
+
47
+ _DEFAULT_URL = "wss://api.vaakini.com"
48
+ _DEFAULT_MODEL = "vaakini-tts-1"
49
+
50
+ # The model's one sample rate: 16-bit mono PCM at 24 kHz.
51
+ _SAMPLE_RATE = 24000
52
+
53
+ # Once a reply's text is all sent, how long Vaakini may send nothing before the service gives up
54
+ # on the connection. Vaakini ends a reply itself, with an error, when the model is late (within a
55
+ # few seconds), so this only catches a server that went silent.
56
+ _SILENCE_TIMEOUT_S = 30.0
57
+
58
+ # After an interruption, how long to wait for Vaakini to confirm the cancel before replacing the
59
+ # connection.
60
+ _CANCEL_TIMEOUT_S = 2.0
61
+
62
+ # How often the receive loop wakes when Vaakini sends nothing: to check those deadlines, which are
63
+ # set from the frame-processing task (a flush, a cancel) while the loop waits, and to keep open
64
+ # the audio contexts of replies Vaakini is still speaking.
65
+ _TICK_S = 1.0
66
+
67
+ # Vaakini's error codes, by what they mean to Pipecat.
68
+ _CATEGORY_FOR_CODE = {
69
+ "bad_request": ErrorCategory.INVALID_REQUEST,
70
+ "unauthorized": ErrorCategory.AUTHENTICATION,
71
+ "insufficient_credits": ErrorCategory.QUOTA,
72
+ "rate_limited": ErrorCategory.RATE_LIMIT,
73
+ "unavailable": ErrorCategory.SERVER,
74
+ "timeout": ErrorCategory.SERVER,
75
+ "internal": ErrorCategory.SERVER,
76
+ }
77
+
78
+
79
+ @dataclass
80
+ class VaakiniTTSSettings(TTSSettings):
81
+ """Settings for ``VaakiniTTSService``, in the names of Vaakini's API.
82
+
83
+ Parameters:
84
+ voice: The voice: a Vaakini voice's name, in any case (``"Monika"``), or the id of one of
85
+ your org's custom voices (``"cv_…"``). ``GET /v1/voices`` lists them.
86
+ language: The language the text is in, one of ``"as"``, ``"bn"``, ``"en"``, ``"gu"``,
87
+ ``"hi"``, ``"kn"``, ``"ml"``, ``"mr"``, ``"or"``, ``"pa"``, ``"ta"`` and ``"te"``, or
88
+ its ``Language``; ``None`` leaves it to the model, which picks it from each sentence's
89
+ script.
90
+ model: The model. ``"vaakini-tts-1"``, the default, is the only one.
91
+ normalize: Speak numbers, currency, dates, times, phone numbers, URLs and emails as words
92
+ in the reply's language. On unless set to False.
93
+ temperature: Sampling temperature, 0.1 to 1.5: lower is steadier.
94
+ top_k: Sample from the k likeliest codes, 1 to 2048.
95
+ top_p: Nucleus sampling, above 0 and at most 1.
96
+ repetition_penalty: Penalty on recently repeated codes, 0 to 5.
97
+
98
+ Each of the last five is sent only when set: ``None`` is the model's own default. In an update
99
+ (``TTSUpdateSettingsFrame``), a setting left out keeps its value, and ``None`` goes back to
100
+ the model's default.
101
+ """
102
+
103
+ normalize: bool | None | NotGiven = field(default_factory=lambda: NOT_GIVEN)
104
+ temperature: float | None | NotGiven = field(default_factory=lambda: NOT_GIVEN)
105
+ top_k: int | None | NotGiven = field(default_factory=lambda: NOT_GIVEN)
106
+ top_p: float | None | NotGiven = field(default_factory=lambda: NOT_GIVEN)
107
+ repetition_penalty: float | None | NotGiven = field(default_factory=lambda: NOT_GIVEN)
108
+
109
+
110
+ # The model's options, as `start` and `warm` name them.
111
+ _OPTIONS = ("normalize", "temperature", "top_k", "top_p", "repetition_penalty")
112
+
113
+
114
+ class _SpokenUsageMetrics(FrameProcessorMetrics):
115
+ """Pipecat reports every character a TTS service is sent as usage, when it is sent. The
116
+ service reports the characters Vaakini spoke instead, when Vaakini ends each reply: an
117
+ interrupted reply then counts only what was spoken."""
118
+
119
+ async def start_tts_usage_metrics(self, text: str) -> MetricsFrame | None:
120
+ return None
121
+
122
+
123
+ @dataclass(eq=False)
124
+ class _Segment:
125
+ """One reply: a TTS context, and the Vaakini segment that speaks it."""
126
+
127
+ context_id: str
128
+ model: str
129
+ # The `start` message.
130
+ start: dict[str, Any] = field(repr=False)
131
+ # Messages held until Vaakini has finished the segments before this one.
132
+ pending: list[str] = field(default_factory=list, repr=False)
133
+ started: bool = False
134
+ flushed: bool = False
135
+ # Interrupted: its audio is discarded until Vaakini confirms the cancel.
136
+ cancelled: bool = False
137
+ # Ended by an error: the rest of its text is dropped and its context ends at the flush.
138
+ failed: bool = False
139
+ # When Vaakini must have sent something (time.monotonic()), once one is due.
140
+ deadline: float | None = None
141
+ audio_bytes: int = 0
142
+ # A trailing byte of a 16-bit sample split across binary frames.
143
+ odd_byte: bytes = b""
144
+ first_text_at: float | None = None
145
+ first_audio_at: float | None = None
146
+
147
+
148
+ class VaakiniTTSService(WebsocketTTSService):
149
+ """Text-to-speech with Vaakini.
150
+
151
+ The LLM's text is streamed to Vaakini as it arrives. Vaakini splits it into sentences and
152
+ speaks each as soon as it is complete, so the first audio follows the reply's first sentence.
153
+ Transcripts follow the audio a sentence at a time.
154
+
155
+ Example::
156
+
157
+ tts = VaakiniTTSService(
158
+ api_key=os.getenv("VAAKINI_API_KEY"),
159
+ settings=VaakiniTTSService.Settings(voice="Monika", language="hi"),
160
+ )
161
+ """
162
+
163
+ Settings = VaakiniTTSSettings
164
+ _settings: Settings
165
+
166
+ def __init__(
167
+ self,
168
+ *,
169
+ api_key: str,
170
+ settings: Settings,
171
+ base_url: str | None = None,
172
+ **kwargs,
173
+ ):
174
+ """Initialize the service.
175
+
176
+ Args:
177
+ api_key: Your Vaakini API key, from the dashboard.
178
+ settings: The voice and settings to speak with. ``voice`` is required.
179
+ base_url: Vaakini's URL. Defaults to ``wss://api.vaakini.com``.
180
+ **kwargs: Additional arguments passed to ``WebsocketTTSService``.
181
+ """
182
+ for name in ("text_aggregation_mode", "aggregate_sentences"):
183
+ if name in kwargs:
184
+ raise TypeError(
185
+ f"{name} is not supported: Vaakini splits sentences itself, so the LLM's "
186
+ "text is streamed to it as it arrives"
187
+ )
188
+ if "metrics" in kwargs:
189
+ raise TypeError("metrics is not supported: the service reports its own usage")
190
+ if "sample_rate" in kwargs:
191
+ raise TypeError(
192
+ "sample_rate is not supported: the model speaks at 24000 Hz, and the pipeline's "
193
+ "output transport resamples it"
194
+ )
195
+ if not api_key:
196
+ raise ValueError("api_key is required: your Vaakini API key")
197
+ if not is_given(settings.voice):
198
+ raise ValueError('settings needs a voice, e.g. Settings(voice="Monika", language="hi")')
199
+ store = self.Settings(
200
+ model=_DEFAULT_MODEL,
201
+ voice=None,
202
+ language=None,
203
+ normalize=None,
204
+ temperature=None,
205
+ top_k=None,
206
+ top_p=None,
207
+ repetition_penalty=None,
208
+ )
209
+ store.apply_update(settings)
210
+ _check_model(store.model)
211
+ _check_voice(store.voice)
212
+
213
+ super().__init__(
214
+ # Vaakini splits the text into sentences itself, so it is sent as it arrives rather
215
+ # than a sentence at a time.
216
+ text_aggregation_mode=TextAggregationMode.TOKEN,
217
+ # Transcripts are pushed as the audio they cover arrives (`add_word_timestamps`).
218
+ push_text_frames=False,
219
+ push_start_frame=True,
220
+ sample_rate=_SAMPLE_RATE,
221
+ settings=store,
222
+ metrics=_SpokenUsageMetrics(),
223
+ **kwargs,
224
+ )
225
+
226
+ self._api_key = api_key
227
+ url = base_url.rstrip("/") if base_url is not None else _DEFAULT_URL
228
+ self._url = f"{url}/v1/stream"
229
+ self._receive_task: asyncio.Task | None = None
230
+ # Connecting happens from the frame-processing task (a reply) and from the receive task (a
231
+ # reconnect); one connection at a time.
232
+ self._connect_lock = asyncio.Lock()
233
+ # Held while a segment's held messages are sent, so a message sent meanwhile can't overtake
234
+ # them.
235
+ self._send_lock = asyncio.Lock()
236
+ # Segments in the order Vaakini serves them: the first is the one it is serving (once
237
+ # started), the rest wait for it to finish.
238
+ self._queue: deque[_Segment] = deque()
239
+ # Segments by context id, until their context ends.
240
+ self._segments: dict[str, _Segment] = {}
241
+
242
+ def can_generate_metrics(self) -> bool:
243
+ """Check if this service can generate processing metrics.
244
+
245
+ Returns:
246
+ True: the service reports TTFB and the characters Vaakini spoke.
247
+ """
248
+ return True
249
+
250
+ def language_to_service_language(self, language: Language) -> str | None:
251
+ """Convert a ``Language`` to Vaakini's code: the bare language, without a region.
252
+
253
+ Args:
254
+ language: The language to convert.
255
+
256
+ Returns:
257
+ The language code, e.g. ``"hi"`` for ``Language.HI_IN``.
258
+ """
259
+ return str(language).partition("-")[0]
260
+
261
+ async def start(self, frame: StartFrame):
262
+ """Connect to Vaakini, which readies the model for the settings at once.
263
+
264
+ Args:
265
+ frame: The start frame.
266
+ """
267
+ await super().start(frame)
268
+ await self._connect()
269
+
270
+ async def _update_settings(self, delta: VaakiniTTSSettings) -> dict[str, Any]:
271
+ """Apply a settings update. Replies that start afterwards use the new settings.
272
+
273
+ Args:
274
+ delta: The settings to change.
275
+
276
+ Returns:
277
+ The changed fields, with their previous values.
278
+ """
279
+ if is_given(delta.model):
280
+ _check_model(delta.model)
281
+ if is_given(delta.voice):
282
+ _check_voice(delta.voice)
283
+ changed = await super()._update_settings(delta)
284
+ self._warn_unhandled_updated_settings(
285
+ changed.keys() - {"model", "voice", "language", *_OPTIONS}
286
+ )
287
+ if changed and not self._queue and self._connected:
288
+ # Vaakini readies the model for the new settings now, so the next reply doesn't wait
289
+ # for it.
290
+ await self._send_warm()
291
+ return changed
292
+
293
+ # ---- connection ----------------------------------------------------------------------------
294
+
295
+ @property
296
+ def _connected(self) -> bool:
297
+ return self._websocket is not None and self._websocket.state is State.OPEN
298
+
299
+ async def _connect(self):
300
+ await super()._connect()
301
+ await self._connect_websocket()
302
+ if self._websocket and (self._receive_task is None or self._receive_task.done()):
303
+ self._receive_task = self.create_task(self._receive_task_handler(self._report_error))
304
+
305
+ async def _disconnect(self):
306
+ await super()._disconnect()
307
+ if self._receive_task:
308
+ await self.cancel_task(self._receive_task)
309
+ self._receive_task = None
310
+ await self._disconnect_websocket()
311
+ self._queue.clear()
312
+ self._segments.clear()
313
+
314
+ async def _connect_websocket(self):
315
+ async with self._connect_lock:
316
+ if self._connected:
317
+ return
318
+ logger.debug(f"{self}: connecting to Vaakini")
319
+ try:
320
+ self._websocket = await self._websocket_connect(
321
+ self._url, additional_headers={"Authorization": f"Bearer {self._api_key}"}
322
+ )
323
+ except InvalidStatus as e:
324
+ # Vaakini refuses a handshake as it refuses any request: a status and its error
325
+ # body. A refusal without one (a proxy's own, say) is reported by its status.
326
+ status = e.response.status_code
327
+ try:
328
+ error = json.loads(e.response.body)["error"]
329
+ message = f"Vaakini {error['code']}: {error['message']}"
330
+ category = _CATEGORY_FOR_CODE.get(error["code"], ErrorCategory.UNKNOWN)
331
+ except (ValueError, KeyError, TypeError):
332
+ message = f"Vaakini refused the connection: HTTP {status}"
333
+ category = classify_http_status_code(status)
334
+ await self._connect_failed(message, category=category)
335
+ return
336
+ except Exception as e:
337
+ await self._connect_failed(
338
+ f"connecting to Vaakini failed: {e}",
339
+ exception=e,
340
+ category=ErrorCategory.CONNECTIVITY,
341
+ )
342
+ return
343
+ await self._call_event_handler("on_connected")
344
+ if self._queue:
345
+ await self._pump()
346
+ else:
347
+ # Vaakini readies the model for these settings now, so the first reply doesn't
348
+ # wait for it.
349
+ await self._send_warm()
350
+
351
+ async def _reconnect_websocket(self, attempt_number: int) -> bool:
352
+ # Only ever after the connection closed. The base class closes the connection before
353
+ # reconnecting, which could close one a reply has just opened.
354
+ logger.warning(f"{self}: reconnecting to Vaakini (attempt {attempt_number})")
355
+ await self._connect_websocket()
356
+ if not await self._verify_connection():
357
+ raise ConnectionError("reconnecting to Vaakini failed")
358
+ return True
359
+
360
+ async def _connect_failed(
361
+ self, message: str, *, category: ErrorCategory, exception: Exception | None = None
362
+ ):
363
+ self._websocket = None
364
+ # The replies waiting for the connection can't be spoken.
365
+ while self._queue:
366
+ await self._fail(self._queue.popleft())
367
+ if self._reconnect_in_progress:
368
+ # The base class reports each reconnect attempt that fails.
369
+ raise ConnectionError(message) from exception
370
+ await self.push_error(error_msg=message, exception=exception, category=category)
371
+ await self._call_event_handler("on_connection_error", message)
372
+
373
+ async def _disconnect_websocket(self):
374
+ try:
375
+ await self.cancel_ttfb_metrics()
376
+ if self._websocket:
377
+ logger.debug(f"{self}: disconnecting from Vaakini")
378
+ await self._websocket.close()
379
+ finally:
380
+ self._websocket = None
381
+ await self._call_event_handler("on_disconnected")
382
+
383
+ async def _send(self, message: dict[str, Any]):
384
+ if not self._websocket:
385
+ raise ConnectionError("not connected to Vaakini")
386
+ await self._websocket.send(json.dumps(message))
387
+
388
+ async def _send_warm(self):
389
+ try:
390
+ await self._send({"type": "warm", **self._start_fields()})
391
+ except ConnectionClosed:
392
+ # The connection is replaced when a reply needs it.
393
+ logger.debug(f"{self}: Vaakini connection closed before warm")
394
+
395
+ async def _send_for(self, segment: _Segment, message: dict[str, Any]):
396
+ """Sends a segment's message, or holds it until Vaakini is serving the segment."""
397
+ async with self._send_lock:
398
+ if not segment.started:
399
+ segment.pending.append(json.dumps(message))
400
+ return
401
+ try:
402
+ await self._send(message)
403
+ except (ConnectionClosed, ConnectionError):
404
+ # The receive loop sees the connection end and fails the segment.
405
+ logger.debug(f"{self}: Vaakini connection closed while sending")
406
+
407
+ async def _pump(self):
408
+ """Starts the first segment at Vaakini once it is free, with its held messages."""
409
+ async with self._send_lock:
410
+ if not self._queue or self._queue[0].started or not self._connected:
411
+ return
412
+ segment = self._queue[0]
413
+ segment.started = True
414
+ try:
415
+ await self._send(segment.start)
416
+ for message in segment.pending:
417
+ assert self._websocket
418
+ await self._websocket.send(message)
419
+ except ConnectionClosed:
420
+ logger.debug(f"{self}: Vaakini connection closed while sending")
421
+ segment.pending.clear()
422
+ if segment.flushed:
423
+ segment.deadline = time.monotonic() + _SILENCE_TIMEOUT_S
424
+
425
+ def _start_fields(self) -> dict[str, Any]:
426
+ # An option that is None is left out: the model's default applies.
427
+ options = {name: getattr(self._settings, name) for name in _OPTIONS}
428
+ fields: dict[str, Any] = {
429
+ "model": self._settings.model,
430
+ "voice": self._settings.voice,
431
+ "sample_rate": _SAMPLE_RATE,
432
+ "format": "pcm",
433
+ "options": {name: value for name, value in options.items() if value is not None},
434
+ }
435
+ if self._settings.language is not None:
436
+ fields["language"] = str(self._settings.language)
437
+ return fields
438
+
439
+ # ---- replies -------------------------------------------------------------------------------
440
+
441
+ @traced_tts
442
+ async def run_tts(self, text: str, context_id: str) -> AsyncGenerator[Frame | None, None]:
443
+ """Send text to Vaakini, in the reply of ``context_id``.
444
+
445
+ Args:
446
+ text: The text, as the LLM streamed it.
447
+ context_id: The reply's TTS context.
448
+
449
+ Yields:
450
+ None: the audio arrives on the receive task.
451
+ """
452
+ segment = self._segments.get(context_id)
453
+ if segment is None:
454
+ # The settings as of the reply's start: an update applies from the next reply.
455
+ model = self._settings.model
456
+ assert isinstance(model, str)
457
+ segment = _Segment(
458
+ context_id=context_id,
459
+ model=model,
460
+ start={"type": "start", "segment_id": context_id, **self._start_fields()},
461
+ )
462
+ self._segments[context_id] = segment
463
+ self._queue.append(segment)
464
+ if self._connected:
465
+ await self._pump()
466
+ else:
467
+ await self._connect()
468
+ if not segment.failed:
469
+ if segment.first_text_at is None:
470
+ segment.first_text_at = time.monotonic()
471
+ await self._send_for(segment, {"type": "text", "segment_id": context_id, "text": text})
472
+ yield None
473
+
474
+ async def flush_audio(self, context_id: str | None = None):
475
+ """End a reply's input: Vaakini speaks what is left of it.
476
+
477
+ Args:
478
+ context_id: The reply's TTS context; the active one if None.
479
+ """
480
+ flush_id = context_id or self.get_active_audio_context_id()
481
+ if flush_id:
482
+ await self._flush(flush_id)
483
+
484
+ async def on_turn_context_completed(self):
485
+ """End the turn's reply, whether or not its audio context is still open."""
486
+ context_id = self._turn_context_id
487
+ await super().on_turn_context_completed()
488
+ # The base class flushes only a reply whose audio context is open; a reply left unflushed
489
+ # would hold up every reply after it at Vaakini.
490
+ if context_id:
491
+ await self._flush(context_id)
492
+
493
+ async def _flush(self, context_id: str):
494
+ segment = self._segments.get(context_id)
495
+ if segment is None:
496
+ # Nothing was sent for the reply (the service had stopped being usable): end the
497
+ # context the base class opened for it.
498
+ if self.audio_context_available(context_id):
499
+ await self.append_to_audio_context(
500
+ context_id, TTSStoppedFrame(context_id=context_id)
501
+ )
502
+ await self.remove_audio_context(context_id)
503
+ return
504
+ if segment.flushed:
505
+ return
506
+ segment.flushed = True
507
+ if segment.failed:
508
+ await self._end_context(segment)
509
+ return
510
+ await self._send_for(segment, {"type": "flush", "segment_id": context_id})
511
+ if segment.started:
512
+ segment.deadline = time.monotonic() + _SILENCE_TIMEOUT_S
513
+
514
+ async def on_audio_context_interrupted(self, context_id: str):
515
+ """Cancel the interrupted reply at Vaakini, which stops speaking it.
516
+
517
+ Args:
518
+ context_id: The interrupted reply's TTS context.
519
+ """
520
+ await self.cancel_ttfb_metrics()
521
+ segment = self._segments.pop(context_id, None)
522
+ if segment is not None and segment in self._queue:
523
+ if segment.started:
524
+ segment.cancelled = True
525
+ segment.deadline = time.monotonic() + _CANCEL_TIMEOUT_S
526
+ await self._send_for(segment, {"type": "cancel", "segment_id": context_id})
527
+ else:
528
+ # Never sent: Vaakini knows nothing of it.
529
+ self._queue.remove(segment)
530
+ await super().on_audio_context_interrupted(context_id)
531
+
532
+ async def _end_context(self, segment: _Segment):
533
+ self._segments.pop(segment.context_id, None)
534
+ if self.audio_context_available(segment.context_id):
535
+ await self.append_to_audio_context(
536
+ segment.context_id, TTSStoppedFrame(context_id=segment.context_id)
537
+ )
538
+ await self.remove_audio_context(segment.context_id)
539
+
540
+ async def _fail(self, segment: _Segment):
541
+ """A segment Vaakini ended with an error, or never got: the rest of its text is dropped,
542
+ and its context ends once its input is done."""
543
+ segment.failed = True
544
+ # No first audio is coming to measure TTFB against.
545
+ await self.cancel_ttfb_metrics()
546
+ if segment.flushed:
547
+ await self._end_context(segment)
548
+
549
+ # ---- receiving -----------------------------------------------------------------------------
550
+
551
+ async def _receive_messages(self):
552
+ while True:
553
+ websocket = self._get_websocket()
554
+ try:
555
+ while True:
556
+ try:
557
+ message = await asyncio.wait_for(websocket.recv(), _TICK_S)
558
+ except TimeoutError:
559
+ self._keep_contexts_open()
560
+ await self._check_deadline(websocket)
561
+ continue
562
+ await self._handle_message(message)
563
+ except ConnectionClosed as e:
564
+ await self._connection_ended()
565
+ # A normal close ends a connection Vaakini is done with: after an error it
566
+ # reported, at its idle timeout, or one this service closed. Replies waiting for
567
+ # it go on a new connection now; otherwise the next reply connects.
568
+ if isinstance(e, ConnectionClosedOK) and self._queue and not self._disconnecting:
569
+ await self._connect_websocket()
570
+ if self._connected:
571
+ continue
572
+ # Anything else (a restart, a network failure) is reconnected by the base class.
573
+ raise
574
+
575
+ def _get_websocket(self):
576
+ if self._websocket:
577
+ return self._websocket
578
+ raise ConnectionError("not connected to Vaakini")
579
+
580
+ def _keep_contexts_open(self):
581
+ # Pipecat ends an audio context that gets no audio for `stop_frame_timeout_s` (3 s), and
582
+ # drops what arrives for it afterwards. Vaakini speaks a reply's sentences one after
583
+ # another, and under load the next one can start later than that, so a reply's context is
584
+ # kept open until Vaakini ends the reply, with the base class's own keepalive,
585
+ # `_refresh_audio_context` (verified on pipecat-ai 1.12.0 and 1.16.0).
586
+ for segment in self._queue:
587
+ if not segment.cancelled:
588
+ self._refresh_audio_context(segment.context_id)
589
+
590
+ async def _check_deadline(self, websocket):
591
+ segment = self._queue[0] if self._queue else None
592
+ if segment is None or segment.deadline is None or time.monotonic() < segment.deadline:
593
+ return
594
+ segment.deadline = None
595
+ if segment.cancelled:
596
+ logger.debug(f"{self}: Vaakini didn't confirm a cancel in time; reconnecting")
597
+ else:
598
+ await self.push_error(
599
+ error_msg="Vaakini sent nothing in time", category=ErrorCategory.SERVER
600
+ )
601
+ self._queue.popleft()
602
+ await self._fail(segment)
603
+ # The receive loop sees the close and moves the replies waiting to a new connection.
604
+ await websocket.close()
605
+
606
+ async def _connection_ended(self):
607
+ """The connection closed: the segment Vaakini was serving is lost."""
608
+ if self._queue and self._queue[0].started:
609
+ segment = self._queue.popleft()
610
+ if not segment.cancelled:
611
+ await self.push_error(
612
+ error_msg="Vaakini closed the connection in the middle of a reply",
613
+ category=ErrorCategory.CONNECTIVITY,
614
+ )
615
+ await self._fail(segment)
616
+
617
+ async def _handle_message(self, message: str | bytes):
618
+ segment = self._queue[0] if self._queue and self._queue[0].started else None
619
+ if isinstance(message, bytes):
620
+ if segment is None:
621
+ logger.warning(f"{self}: Vaakini sent audio outside a reply")
622
+ return
623
+ self._extend_deadline(segment)
624
+ if not segment.cancelled:
625
+ await self._push_audio(segment, message)
626
+ return
627
+
628
+ data = json.loads(message)
629
+ kind = data["type"]
630
+ if kind == "error":
631
+ await self._api_error(data, segment)
632
+ return
633
+ if segment is None:
634
+ logger.warning(f"{self}: unexpected Vaakini message {kind!r} outside a reply")
635
+ return
636
+ self._extend_deadline(segment)
637
+ if kind == "sentence":
638
+ if not segment.cancelled:
639
+ await self._sentence(segment, data["text"])
640
+ elif kind == "done":
641
+ self._queue.popleft()
642
+ await self._done(segment, data)
643
+ await self._pump()
644
+ elif kind == "cancelled":
645
+ # A cancel that crossed the segment's `done` is confirmed after it, naming a segment
646
+ # already gone (with zeros: `done` reported the counts).
647
+ if data["segment_id"] == segment.context_id:
648
+ self._queue.popleft()
649
+ # The sentences sent in full before the cancel.
650
+ await self._report(segment, data, cancelled=True)
651
+ await self._pump()
652
+ else:
653
+ logger.warning(f"{self}: unexpected Vaakini message {kind!r}")
654
+
655
+ def _extend_deadline(self, segment: _Segment):
656
+ if segment.deadline is not None and not segment.cancelled:
657
+ segment.deadline = time.monotonic() + _SILENCE_TIMEOUT_S
658
+
659
+ async def _push_audio(self, segment: _Segment, data: bytes):
660
+ if segment.first_audio_at is None:
661
+ segment.first_audio_at = time.monotonic()
662
+ data = segment.odd_byte + data
663
+ whole = len(data) & ~1
664
+ segment.odd_byte = data[whole:]
665
+ if not whole:
666
+ return
667
+ segment.audio_bytes += whole
668
+ await self.append_to_audio_context(
669
+ segment.context_id,
670
+ TTSAudioRawFrame(
671
+ audio=data[:whole],
672
+ sample_rate=_SAMPLE_RATE,
673
+ num_channels=1,
674
+ context_id=segment.context_id,
675
+ ),
676
+ )
677
+
678
+ async def _sentence(self, segment: _Segment, text: str):
679
+ # Transcripts follow the audio a sentence at a time: its words, as it starts.
680
+ sentence_start = segment.audio_bytes / 2 / _SAMPLE_RATE
681
+ await self.add_word_timestamps(
682
+ [(word, sentence_start) for word in text.split()], segment.context_id
683
+ )
684
+
685
+ async def _done(self, segment: _Segment, data: dict[str, Any]):
686
+ await self._report(segment, data, cancelled=False)
687
+ if segment.cancelled:
688
+ return
689
+ if segment.odd_byte:
690
+ logger.warning(f"{self}: Vaakini audio ended in the middle of a sample")
691
+ await self._end_context(segment)
692
+
693
+ async def _report(self, segment: _Segment, counts: dict[str, Any], *, cancelled: bool):
694
+ """Usage from `done`'s or `cancelled`'s counts: the characters Vaakini spoke, which are
695
+ the ones it charges for."""
696
+ if self.can_generate_metrics() and self.usage_metrics_enabled:
697
+ await self.push_frame(
698
+ MetricsFrame(
699
+ data=[
700
+ TTSUsageMetricsData(
701
+ processor=self.name,
702
+ model=segment.model,
703
+ value=counts["characters"],
704
+ )
705
+ ]
706
+ )
707
+ )
708
+ first_audio_ms = (
709
+ round((segment.first_audio_at - segment.first_text_at) * 1000)
710
+ if segment.first_audio_at is not None and segment.first_text_at is not None
711
+ else None
712
+ )
713
+ logger.debug(
714
+ f"{self}: reply {segment.context_id} {'cancelled' if cancelled else 'done'}: "
715
+ f"{counts['sentences']} sentences, {counts['characters']} characters, "
716
+ f"first audio after {first_audio_ms} ms"
717
+ )
718
+
719
+ async def _api_error(self, data: dict[str, Any], segment: _Segment | None):
720
+ code = data["code"]
721
+ category = _CATEGORY_FOR_CODE.get(code, ErrorCategory.UNKNOWN)
722
+ message = f"Vaakini {code}: {data['message']}"
723
+ # Vaakini closes the connection after an error; the receive loop moves the replies waiting
724
+ # to a new one.
725
+ if segment is not None and data["segment_id"] == segment.context_id:
726
+ self._queue.popleft()
727
+ if segment.cancelled:
728
+ logger.debug(f"{self}: interrupted reply ended with {code}")
729
+ return
730
+ await self.push_error(error_msg=message, category=category)
731
+ await self._fail(segment)
732
+ else:
733
+ # A `warm` Vaakini refused (a voice the org can't speak, an option out of range), or
734
+ # an error about the connection itself. Vaakini closes the connection after it; a
735
+ # reply connects again and is refused itself if the settings are still wrong.
736
+ await self.push_error(error_msg=message, category=category)
737
+
738
+
739
+ def _check_model(model: str | None | NotGiven):
740
+ if not isinstance(model, str) or not model:
741
+ raise ValueError(f'model must be a model id, e.g. "vaakini-tts-1"; got {model!r}')
742
+
743
+
744
+ def _check_voice(voice: str | None | NotGiven):
745
+ if not isinstance(voice, str) or not voice:
746
+ raise ValueError(f"voice must be a voice's name or a custom voice's id; got {voice!r}")
@@ -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 = "pipecat-vaakini"
7
+ dynamic = ["version"]
8
+ description = "Pipecat TTS service 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.11"
12
+ authors = [{ name = "Oggnai Technologies Private Limited" }]
13
+ keywords = [
14
+ "voice",
15
+ "ai",
16
+ "realtime",
17
+ "audio",
18
+ "pipecat",
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.11",
32
+ "Programming Language :: Python :: 3 :: Only",
33
+ ]
34
+ dependencies = ["pipecat-ai>=1.12.0"]
35
+
36
+ [project.urls]
37
+ Homepage = "https://vaakini.com"
38
+ Documentation = "https://docs.vaakini.com/pipecat"
39
+
40
+ [tool.hatch.version]
41
+ path = "pipecat_vaakini/version.py"
42
+
43
+ [tool.hatch.build.targets.wheel]
44
+ packages = ["pipecat_vaakini"]
45
+
46
+ [tool.hatch.build.targets.sdist]
47
+ include = ["/pipecat_vaakini", "/CHANGELOG.md"]