anyvoice 0.0.2__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.
anyvoice-0.0.2/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024, Philipp Temminghoff
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
@@ -0,0 +1,67 @@
1
+ Metadata-Version: 2.4
2
+ Name: anyvoice
3
+ Version: 0.0.2
4
+ Summary: Common interface for streaming tts providers
5
+ Keywords:
6
+ Author: Philipp Temminghoff
7
+ Author-email: Philipp Temminghoff <philipptemminghoff@googlemail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Framework :: Pydantic
12
+ Classifier: Framework :: Pydantic :: 2
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Documentation
21
+ Classifier: Topic :: Software Development
22
+ Classifier: Topic :: Utilities
23
+ Classifier: Typing :: Typed
24
+ Requires-Dist: pydantic
25
+ Requires-Dist: schemez
26
+ Requires-Dist: openai>=1.0.0 ; extra == 'openai'
27
+ Requires-Dist: sounddevice>=0.5.0 ; extra == 'openai'
28
+ Requires-Dist: numpy>=1.24.0 ; extra == 'openai'
29
+ Requires-Dist: edge-tts>=7.0.0 ; extra == 'tts-edge'
30
+ Requires-Dist: miniaudio>=1.60 ; extra == 'tts-edge'
31
+ Requires-Dist: sounddevice>=0.5.0 ; extra == 'tts-edge'
32
+ Requires-Python: >=3.13
33
+ Project-URL: Code coverage, https://app.codecov.io/gh/phil65/anyvoice
34
+ Project-URL: Discussions, https://github.com/phil65/anyvoice/discussions
35
+ Project-URL: Documentation, https://phil65.github.io/anyvoice/
36
+ Project-URL: Issues, https://github.com/phil65/anyvoice/issues
37
+ Project-URL: Source, https://github.com/phil65/anyvoice
38
+ Provides-Extra: openai
39
+ Provides-Extra: tts-edge
40
+ Description-Content-Type: text/markdown
41
+
42
+ # AnyVoice
43
+
44
+ [![PyPI License](https://img.shields.io/pypi/l/anyvoice.svg)](https://pypi.org/project/anyvoice/)
45
+ [![Package status](https://img.shields.io/pypi/status/anyvoice.svg)](https://pypi.org/project/anyvoice/)
46
+ [![Monthly downloads](https://img.shields.io/pypi/dm/anyvoice.svg)](https://pypi.org/project/anyvoice/)
47
+ [![Distribution format](https://img.shields.io/pypi/format/anyvoice.svg)](https://pypi.org/project/anyvoice/)
48
+ [![Wheel availability](https://img.shields.io/pypi/wheel/anyvoice.svg)](https://pypi.org/project/anyvoice/)
49
+ [![Python version](https://img.shields.io/pypi/pyversions/anyvoice.svg)](https://pypi.org/project/anyvoice/)
50
+ [![Implementation](https://img.shields.io/pypi/implementation/anyvoice.svg)](https://pypi.org/project/anyvoice/)
51
+ [![Releases](https://img.shields.io/github/downloads/phil65/anyvoice/total.svg)](https://github.com/phil65/anyvoice/releases)
52
+ [![Github Contributors](https://img.shields.io/github/contributors/phil65/anyvoice)](https://github.com/phil65/anyvoice/graphs/contributors)
53
+ [![Github Discussions](https://img.shields.io/github/discussions/phil65/anyvoice)](https://github.com/phil65/anyvoice/discussions)
54
+ [![Github Forks](https://img.shields.io/github/forks/phil65/anyvoice)](https://github.com/phil65/anyvoice/forks)
55
+ [![Github Issues](https://img.shields.io/github/issues/phil65/anyvoice)](https://github.com/phil65/anyvoice/issues)
56
+ [![Github Issues](https://img.shields.io/github/issues-pr/phil65/anyvoice)](https://github.com/phil65/anyvoice/pulls)
57
+ [![Github Watchers](https://img.shields.io/github/watchers/phil65/anyvoice)](https://github.com/phil65/anyvoice/watchers)
58
+ [![Github Stars](https://img.shields.io/github/stars/phil65/anyvoice)](https://github.com/phil65/anyvoice/stars)
59
+ [![Github Repository size](https://img.shields.io/github/repo-size/phil65/anyvoice)](https://github.com/phil65/anyvoice)
60
+ [![Github last commit](https://img.shields.io/github/last-commit/phil65/anyvoice)](https://github.com/phil65/anyvoice/commits)
61
+ [![Github release date](https://img.shields.io/github/release-date/phil65/anyvoice)](https://github.com/phil65/anyvoice/releases)
62
+ [![Github language count](https://img.shields.io/github/languages/count/phil65/anyvoice)](https://github.com/phil65/anyvoice)
63
+ [![Github commits this month](https://img.shields.io/github/commit-activity/m/phil65/anyvoice)](https://github.com/phil65/anyvoice)
64
+ [![Package status](https://codecov.io/gh/phil65/anyvoice/branch/main/graph/badge.svg)](https://codecov.io/gh/phil65/anyvoice/)
65
+ [![PyUp](https://pyup.io/repos/github/phil65/anyvoice/shield.svg)](https://pyup.io/repos/github/phil65/anyvoice/)
66
+
67
+ [Read the documentation!](https://phil65.github.io/anyvoice/)
@@ -0,0 +1,26 @@
1
+ # AnyVoice
2
+
3
+ [![PyPI License](https://img.shields.io/pypi/l/anyvoice.svg)](https://pypi.org/project/anyvoice/)
4
+ [![Package status](https://img.shields.io/pypi/status/anyvoice.svg)](https://pypi.org/project/anyvoice/)
5
+ [![Monthly downloads](https://img.shields.io/pypi/dm/anyvoice.svg)](https://pypi.org/project/anyvoice/)
6
+ [![Distribution format](https://img.shields.io/pypi/format/anyvoice.svg)](https://pypi.org/project/anyvoice/)
7
+ [![Wheel availability](https://img.shields.io/pypi/wheel/anyvoice.svg)](https://pypi.org/project/anyvoice/)
8
+ [![Python version](https://img.shields.io/pypi/pyversions/anyvoice.svg)](https://pypi.org/project/anyvoice/)
9
+ [![Implementation](https://img.shields.io/pypi/implementation/anyvoice.svg)](https://pypi.org/project/anyvoice/)
10
+ [![Releases](https://img.shields.io/github/downloads/phil65/anyvoice/total.svg)](https://github.com/phil65/anyvoice/releases)
11
+ [![Github Contributors](https://img.shields.io/github/contributors/phil65/anyvoice)](https://github.com/phil65/anyvoice/graphs/contributors)
12
+ [![Github Discussions](https://img.shields.io/github/discussions/phil65/anyvoice)](https://github.com/phil65/anyvoice/discussions)
13
+ [![Github Forks](https://img.shields.io/github/forks/phil65/anyvoice)](https://github.com/phil65/anyvoice/forks)
14
+ [![Github Issues](https://img.shields.io/github/issues/phil65/anyvoice)](https://github.com/phil65/anyvoice/issues)
15
+ [![Github Issues](https://img.shields.io/github/issues-pr/phil65/anyvoice)](https://github.com/phil65/anyvoice/pulls)
16
+ [![Github Watchers](https://img.shields.io/github/watchers/phil65/anyvoice)](https://github.com/phil65/anyvoice/watchers)
17
+ [![Github Stars](https://img.shields.io/github/stars/phil65/anyvoice)](https://github.com/phil65/anyvoice/stars)
18
+ [![Github Repository size](https://img.shields.io/github/repo-size/phil65/anyvoice)](https://github.com/phil65/anyvoice)
19
+ [![Github last commit](https://img.shields.io/github/last-commit/phil65/anyvoice)](https://github.com/phil65/anyvoice/commits)
20
+ [![Github release date](https://img.shields.io/github/release-date/phil65/anyvoice)](https://github.com/phil65/anyvoice/releases)
21
+ [![Github language count](https://img.shields.io/github/languages/count/phil65/anyvoice)](https://github.com/phil65/anyvoice)
22
+ [![Github commits this month](https://img.shields.io/github/commit-activity/m/phil65/anyvoice)](https://github.com/phil65/anyvoice)
23
+ [![Package status](https://codecov.io/gh/phil65/anyvoice/branch/main/graph/badge.svg)](https://codecov.io/gh/phil65/anyvoice/)
24
+ [![PyUp](https://pyup.io/repos/github/phil65/anyvoice/shield.svg)](https://pyup.io/repos/github/phil65/anyvoice/)
25
+
26
+ [Read the documentation!](https://phil65.github.io/anyvoice/)
@@ -0,0 +1,303 @@
1
+ #:tombi schema.strict = false
2
+
3
+ [project]
4
+ name = "anyvoice"
5
+ version = "0.0.2"
6
+ description = "Common interface for streaming tts providers"
7
+ readme = "README.md"
8
+ requires-python = ">=3.13"
9
+ license = "MIT"
10
+ license-files = ["LICENSE"]
11
+ authors = [
12
+ { name = "Philipp Temminghoff", email = "philipptemminghoff@googlemail.com" },
13
+ ]
14
+ keywords = []
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Framework :: Pydantic",
18
+ "Framework :: Pydantic :: 2",
19
+ "Intended Audience :: Developers",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3 :: Only",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Programming Language :: Python :: 3.14",
26
+ "Topic :: Documentation",
27
+ "Topic :: Software Development",
28
+ "Topic :: Utilities",
29
+ "Typing :: Typed",
30
+ ]
31
+ dependencies = [
32
+ "pydantic",
33
+ "schemez",
34
+ # Only add below (Copier)
35
+ ]
36
+
37
+ [project.urls]
38
+ "Code coverage" = "https://app.codecov.io/gh/phil65/anyvoice"
39
+ Discussions = "https://github.com/phil65/anyvoice/discussions"
40
+ Documentation = "https://phil65.github.io/anyvoice/"
41
+ Issues = "https://github.com/phil65/anyvoice/issues"
42
+ Source = "https://github.com/phil65/anyvoice"
43
+
44
+ [project.optional-dependencies]
45
+ openai = [
46
+ "openai>=1.0.0",
47
+ "sounddevice>=0.5.0",
48
+ "numpy>=1.24.0"
49
+ ] # Text-to-Speech with OpenAI
50
+ tts-edge = [
51
+ "edge-tts>=7.0.0",
52
+ "miniaudio>=1.60",
53
+ "sounddevice>=0.5.0",
54
+ ] # Text-to-Speech with Edge TTS (free, no API key)
55
+
56
+ [dependency-groups]
57
+ dev = [
58
+ "devtools",
59
+ "pyreadline3",
60
+ "pytest",
61
+ "pytest-cov",
62
+ # Only add below (Copier)
63
+ ]
64
+ benchmark = ["pyinstrument"]
65
+ docs = [
66
+ "mkdocs-material",
67
+ "mkdocs-mknodes",
68
+ # Only add below (Copier)
69
+ ]
70
+ lint = [
71
+ "mypy; python_version >= '3.14'",
72
+ "mypy[faster-cache]; python_version < '3.14'",
73
+ "ruff",
74
+ # Only add below (Copier)
75
+ ]
76
+
77
+ [build-system]
78
+ requires = ["uv_build>=0.8.22"]
79
+ build-backend = "uv_build"
80
+
81
+ [tool.coverage.report]
82
+ exclude_lines = [
83
+ "pragma: no cover",
84
+ "if TYPE_CHECKING:",
85
+ "@overload",
86
+ "except ImportError",
87
+ 'if __name__ == "__main__":',
88
+ ]
89
+
90
+ [tool.mknodes]
91
+ allowed-commit-types = [
92
+ "fix",
93
+ "feat",
94
+ "refactor",
95
+ "docs",
96
+ "test",
97
+ "build",
98
+ "chore",
99
+ ]
100
+ docstring-style = "google"
101
+
102
+ [tool.mypy]
103
+ python_version = "3.13"
104
+ disable_error_code = ["misc", "import"]
105
+ pretty = true
106
+ check_untyped_defs = true
107
+ exclude = ["venv/", ".venv/", "tests/"]
108
+ plugins = ["pydantic.mypy"]
109
+
110
+ [tool.pyright]
111
+ venvPath = "."
112
+ venv = ".venv"
113
+ pythonVersion = "3.13"
114
+ pythonPlatform = "All"
115
+ typeCheckingMode = "basic"
116
+ deprecateTypingAliases = true
117
+ reportMissingTypeStubs = false
118
+ reportUnusedCallResult = false
119
+ reportUnknownVariableType = false
120
+ reportAny = false
121
+ reportImplicitOverride = false
122
+ reportUnusedFunction = false
123
+ reportImplicitStringConcatenation = false
124
+ reportIgnoreCommentWithoutRule = false
125
+ reportUnannotatedClassAttribute = false
126
+ reportSelfClsParameterName = false
127
+ reportPrivateImportUsage = false
128
+
129
+ [tool.pytest]
130
+ log_cli = true
131
+ log_date_format = "%Y-%m-%d %H:%M:%S"
132
+ log_format = "%(asctime)s %(levelname)s %(message)s"
133
+ minversion = "9.0"
134
+ testpaths = ["tests/"]
135
+ asyncio_mode = "auto"
136
+
137
+ [tool.ruff]
138
+ line-length = 100
139
+ extend-exclude = ["docs"]
140
+ target-version = "py313"
141
+
142
+ [tool.ruff.lint]
143
+ future-annotations = true
144
+ select = [
145
+ "A", # Flake8-builtins
146
+ # "ANN", # Flake8-Annotations
147
+ # "ASYNC", # Flake8-Async
148
+ # "ARG", # # Flake8-Unused-Arguments
149
+ "B", # flake8-bugbear
150
+ "BLE", # Flake8-blind-except
151
+ "C",
152
+ "C4", # flake8-comprehensions
153
+ # "C90", # MCCabe
154
+ "COM", # Flake8-commas
155
+ # "CPY", # Copyright-related rules
156
+ "D", # PyDocStyle
157
+ # "DTZ", # Flake8- Datetimez
158
+ "E", # PyCodeStyle Error
159
+ "EM", # flake8-errmsg
160
+ # "ERA", # Eradicate
161
+ "EXE", # flake8-executable
162
+ "F", # PyFlakes
163
+ "FA", # flake8-future-annotations
164
+ # "FBT", # flake8-boolean-trap
165
+ # "FIX", # flake8-fixme
166
+ "FLY", # flynt
167
+ "G", # flake8-logging-format
168
+ "I", # ISort
169
+ "ICN", # Flake8-import-conventions
170
+ "INP", # flake8-no-pep420
171
+ "INT", # flake8-gettext
172
+ "ISC", # flake8-implicit-str-concat
173
+ "N", # pep8-naming
174
+ # "NPY", # numpy-specific rules
175
+ # "PD", # pandas-vet
176
+ "PERF", # perflint
177
+ # "PGH", # pygrep-hooks
178
+ "PIE", # flake8-pie
179
+ "PLE", # PyLint Error
180
+ "PLC", # PyLint convention
181
+ # "PLW", # PyLint Warning
182
+ "PLR", # PyLint refactor
183
+ "PT", # flake8-pytest-style
184
+ "PTH", # flake8-use-pathlib
185
+ "PYI", # flake8-pyi
186
+ "Q", # flake8-quotes
187
+ "RET", # flake8-return
188
+ "RSE", # flake8-raise
189
+ "RUF", # ruff-specific rules
190
+ # "S", # flake8-bandit
191
+ "SIM", # flake8-simplify
192
+ "SLF", # flake8-self
193
+ "SLOT", # flake8-slots
194
+ # "T",
195
+ # "TD", # flake8-todos
196
+ "T10", # flake8-debugger
197
+ # "T20", # flake8-print
198
+ "TC", # flake8-type-checking
199
+ "TID", # flake8-tidy-imports
200
+ "TRY", # tryceratops
201
+ "UP", # PyUpgrade
202
+ "W", # PyCodeStyle warning
203
+ "YTT", # flake8-2020
204
+ ]
205
+ ignore = [
206
+ "C408", # Unnecessary {obj_type} call (rewrite as a literal)
207
+ "B905", # zip() without an explicit strict= parameter
208
+ "C901", # {name} is too complex ({complexity} > {max_complexity})
209
+ "COM812",
210
+ # "CPY001", # Missing copyright notice at top of file
211
+ "D100", # Missing docstring in public module
212
+ "D101", # Missing docstring in public class
213
+ "D102", # Missing docstring in public method
214
+ "D103", # Missing docstring in public function
215
+ "D104", # Missing docstring in public package
216
+ "D105", # Missing docstring in magic method
217
+ "D106", # Missing docstring in public nested class
218
+ "D107", # Missing docstring in __init__
219
+ "D203", # 1 blank line required before class docstring
220
+ "D204", # 1 blank line required after class docstring
221
+ "D213", # Multi-line docstring summary should start at the second line
222
+ "D215", # Section underline is over-indented ("{name}")
223
+ "D400", # First line should end with a period
224
+ "D401", # First line of docstring should be in imperative mood: "{first_line}"
225
+ "D404", # First word of the docstring should not be "This"
226
+ "D406", # Section name should end with a newline ("{name}")
227
+ "D407", # Missing dashed underline after section ("{name}")
228
+ "D408", # Section underline should be in the line following the section's name ("{name}")
229
+ "D409", # Section underline should match the length of its name ("{name}")
230
+ "D413", # Missing blank line after last section ("{name}")
231
+ "EM101", # Exception must not use a string literal, assign to variable first
232
+ "EM102", # Exception must not use an f-string literal, assign to variable first
233
+ "ISC001",
234
+ "PLC0415",
235
+ "PLR0912", # Too many branches
236
+ "PLR0913", # Too many arguments to function call
237
+ "PLR0915", # Too many statements
238
+ # "PLR2004", # Magic values instead of named consts
239
+ "SLF001", # Private member accessed
240
+ "TRY003", # Avoid specifying long messages outside the exception class
241
+ "TC006", # runtime-cast-value
242
+ ]
243
+
244
+ [tool.ruff.lint.flake8-quotes]
245
+ docstring-quotes = "double"
246
+
247
+ [tool.ruff.lint.flake8-type-checking]
248
+ runtime-evaluated-base-classes = [
249
+ "pydantic.BaseModel",
250
+ "sqlalchemy.orm.DeclarativeBase",
251
+ "schemez.Schema",
252
+ "sqlmodel.SQLModel",
253
+ ]
254
+ runtime-evaluated-decorators = [
255
+ "pydantic.validate_call",
256
+ "fastapi.FastAPI.get",
257
+ "fastapi.FastAPI.post",
258
+ "fastmcp.FastMCP.tool",
259
+ "typer.Typer.command",
260
+ ]
261
+
262
+ [tool.ruff.lint.isort]
263
+ lines-after-imports = 2
264
+ # lines-between-types = 1
265
+ # atomic = true
266
+ force-sort-within-sections = true
267
+ combine-as-imports = true
268
+
269
+ [tool.ruff.lint.mccabe]
270
+ max-complexity = 15
271
+
272
+ [tool.ruff.lint.per-file-ignores]
273
+ "__init__.py" = ["E402", "I001"]
274
+ "scripts/*" = ["INP001"]
275
+ "*tests/*" = ["D100"]
276
+
277
+ [tool.ruff.format]
278
+ preview = true
279
+
280
+ [tool.ty.environment]
281
+ python-version = "3.13"
282
+ python-platform = "all"
283
+
284
+ [tool.uv]
285
+ default-groups = ["dev", "lint", "docs"]
286
+
287
+ [tool.uv.build-backend]
288
+ wheel-exclude = [
289
+ ".mypy_cache/**",
290
+ "__pycache__/**",
291
+ "*.pyc",
292
+ "*.pyo",
293
+ ".pytest_cache/**",
294
+ ".ruff_cache/**",
295
+ ]
296
+ source-exclude = [
297
+ ".mypy_cache/**",
298
+ "__pycache__/**",
299
+ "*.pyc",
300
+ "*.pyo",
301
+ ".pytest_cache/**",
302
+ ".ruff_cache/**",
303
+ ]
@@ -0,0 +1,55 @@
1
+ """AnyVoice: A streaming-friendly Text-to-Speech library.
2
+
3
+ This library provides a clean, composable API for TTS synthesis with:
4
+ - Multiple provider backends (OpenAI, Edge TTS)
5
+ - Pluggable audio sinks (speakers, file, callback)
6
+ - Streaming support with sentence buffering
7
+ - Configurable synchronization modes
8
+
9
+ Example:
10
+ from anyvoice import TTSStream, OpenAITTSProvider, SoundDeviceSink
11
+
12
+ provider = OpenAITTSProvider(api_key="...")
13
+ session = provider.session(voice="nova")
14
+
15
+ async with TTSStream(session, sink=SoundDeviceSink()) as tts:
16
+ await tts.feed("Hello ")
17
+ await tts.feed("world!")
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from importlib.metadata import version
23
+
24
+ from anyvoice.base import AudioSink, TTSProvider, TTSSession
25
+ from anyvoice.providers import EdgeTTSProvider, OpenAITTSProvider
26
+ from anyvoice.sinks import CallbackSink, FileSink, SoundDeviceSink
27
+ from anyvoice.stream import TTSMode, TTSStream
28
+
29
+
30
+ __version__ = version("anyvoice")
31
+ __title__ = "AnyVoice"
32
+
33
+ __author__ = "Philipp Temminghoff"
34
+ __author_email__ = "philipptemminghoff@googlemail.com"
35
+ __copyright__ = "Copyright (c) 2025 Philipp Temminghoff"
36
+ __license__ = "MIT"
37
+ __url__ = "https://github.com/phil65/anyvoice"
38
+
39
+
40
+ __all__ = [
41
+ # Base classes
42
+ "AudioSink",
43
+ # Sinks
44
+ "CallbackSink",
45
+ # Providers
46
+ "EdgeTTSProvider",
47
+ "FileSink",
48
+ "OpenAITTSProvider",
49
+ "SoundDeviceSink",
50
+ # Orchestrator
51
+ "TTSMode",
52
+ "TTSProvider",
53
+ "TTSSession",
54
+ "TTSStream",
55
+ ]
@@ -0,0 +1,106 @@
1
+ """Base classes for TTS providers and audio sinks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from typing import TYPE_CHECKING, Any, Self
7
+
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import AsyncIterator
11
+ from types import TracebackType
12
+
13
+
14
+ class AudioSink(ABC):
15
+ """Abstract base class for audio output backends.
16
+
17
+ Audio sinks receive PCM audio chunks and handle output
18
+ (playback, file writing, etc.).
19
+
20
+ Usage as context manager:
21
+ async with SoundDeviceSink() as sink:
22
+ await sink.write(audio_chunk)
23
+ """
24
+
25
+ async def __aenter__(self) -> Self:
26
+ """Enter the sink context, prepare for receiving audio."""
27
+ return self
28
+
29
+ async def __aexit__( # noqa: B027
30
+ self,
31
+ exc_type: type[BaseException] | None,
32
+ exc_val: BaseException | None,
33
+ exc_tb: TracebackType | None,
34
+ ) -> None:
35
+ """Exit the sink context, finalize and cleanup."""
36
+
37
+ @abstractmethod
38
+ async def write(self, chunk: bytes) -> None:
39
+ """Write a PCM audio chunk to the sink.
40
+
41
+ Args:
42
+ chunk: Raw PCM audio data (16-bit signed, mono).
43
+ """
44
+ ...
45
+
46
+
47
+ class TTSSession(ABC):
48
+ """Abstract base class for TTS synthesis sessions.
49
+
50
+ A session represents a single synthesis context with specific
51
+ configuration (voice, speed, etc.). Sessions are lightweight
52
+ and created by providers.
53
+
54
+ Usage:
55
+ session = provider.session(voice="nova")
56
+ async for chunk in session.synthesize("Hello world"):
57
+ await sink.write(chunk)
58
+ """
59
+
60
+ async def __aenter__(self) -> Self:
61
+ """Enter the session context."""
62
+ return self
63
+
64
+ async def __aexit__( # noqa: B027
65
+ self,
66
+ exc_type: type[BaseException] | None,
67
+ exc_val: BaseException | None,
68
+ exc_tb: TracebackType | None,
69
+ ) -> None:
70
+ """Exit the session context, cleanup resources."""
71
+
72
+ @abstractmethod
73
+ def synthesize(self, text: str) -> AsyncIterator[bytes]:
74
+ """Synthesize text to PCM audio.
75
+
76
+ Args:
77
+ text: Text to synthesize.
78
+
79
+ Yields:
80
+ PCM audio chunks (16-bit signed, mono).
81
+ """
82
+ ...
83
+
84
+
85
+ class TTSProvider(ABC):
86
+ """Abstract base class for TTS providers.
87
+
88
+ Providers hold credentials and client configuration, and act
89
+ as factories for lightweight sessions.
90
+
91
+ Usage:
92
+ provider = OpenAITTSProvider(api_key="...")
93
+ session = provider.session(voice="nova", speed=1.0)
94
+ """
95
+
96
+ @abstractmethod
97
+ def session(self, **config: Any) -> TTSSession:
98
+ """Create a new synthesis session with the given configuration.
99
+
100
+ Args:
101
+ **config: Provider-specific configuration (voice, speed, etc.).
102
+
103
+ Returns:
104
+ A new TTSSession configured with the given parameters.
105
+ """
106
+ ...
@@ -0,0 +1,25 @@
1
+ """Logging configuration for anyvoice."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+
7
+
8
+ LogLevel = int | str
9
+
10
+
11
+ def get_logger(name: str, log_level: LogLevel | None = None) -> logging.Logger:
12
+ """Get a logger for the given name.
13
+
14
+ Args:
15
+ name: The name of the logger.
16
+ Will be prefixed with 'anyvoice'
17
+ log_level: The logging level to set for the logger
18
+
19
+ Returns:
20
+ A logger instance
21
+ """
22
+ logger = logging.getLogger(f"anyvoice.{name}")
23
+ if log_level is not None:
24
+ logger.setLevel(log_level)
25
+ return logger
@@ -0,0 +1,6 @@
1
+ """TTS provider implementations."""
2
+
3
+ from anyvoice.providers.edge import EdgeTTSProvider
4
+ from anyvoice.providers.openai import OpenAITTSProvider
5
+
6
+ __all__ = ["EdgeTTSProvider", "OpenAITTSProvider"]
@@ -0,0 +1,155 @@
1
+ """Edge TTS provider implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, Self
6
+
7
+ from anyvoice.base import TTSProvider, TTSSession
8
+
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import AsyncIterator
12
+ from types import TracebackType
13
+
14
+
15
+ class EdgeTTSSession(TTSSession):
16
+ """TTS session using Microsoft Edge's TTS service.
17
+
18
+ Args:
19
+ voice: Voice name (e.g., "en-US-AriaNeural").
20
+ rate: Speaking rate adjustment (e.g., "+25%", "-10%").
21
+ volume: Volume adjustment (e.g., "+10%", "-20%").
22
+ pitch: Pitch adjustment in Hz (e.g., "+10Hz", "-5Hz").
23
+ sample_rate: Target sample rate for decoded audio.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ *,
29
+ voice: str = "en-US-AriaNeural",
30
+ rate: str = "+0%",
31
+ volume: str = "+0%",
32
+ pitch: str = "+0Hz",
33
+ sample_rate: int = 24000,
34
+ ) -> None:
35
+ self._voice = voice
36
+ self._rate = rate
37
+ self._volume = volume
38
+ self._pitch = pitch
39
+ self._sample_rate = sample_rate
40
+
41
+ async def synthesize(self, text: str) -> AsyncIterator[bytes]:
42
+ """Synthesize text to PCM audio using Edge TTS.
43
+
44
+ Edge TTS returns MP3 which is decoded to PCM via miniaudio.
45
+
46
+ Args:
47
+ text: Text to synthesize.
48
+
49
+ Yields:
50
+ PCM audio chunks (16-bit signed, mono).
51
+ """
52
+ import edge_tts
53
+ import miniaudio # type: ignore[import-untyped]
54
+
55
+ if not text.strip():
56
+ return
57
+
58
+ communicate = edge_tts.Communicate(
59
+ text,
60
+ voice=self._voice,
61
+ rate=self._rate,
62
+ volume=self._volume,
63
+ pitch=self._pitch,
64
+ )
65
+
66
+ # Collect MP3 chunks
67
+ mp3_data = bytearray()
68
+ async for chunk in communicate.stream():
69
+ if chunk["type"] == "audio":
70
+ assert "data" in chunk
71
+ mp3_data.extend(chunk["data"])
72
+
73
+ if mp3_data:
74
+ # Decode MP3 to mono 16-bit PCM at target sample rate
75
+ decoded = miniaudio.decode(
76
+ bytes(mp3_data),
77
+ output_format=miniaudio.SampleFormat.SIGNED16,
78
+ nchannels=1,
79
+ sample_rate=self._sample_rate,
80
+ )
81
+ yield decoded.samples.tobytes()
82
+
83
+
84
+ class EdgeTTSProvider(TTSProvider):
85
+ """TTS provider using Microsoft Edge's free TTS service.
86
+
87
+ Uses edge-tts library to access Microsoft's neural TTS voices.
88
+ No API key required.
89
+
90
+ Args:
91
+ default_voice: Default voice name. Defaults to "en-US-AriaNeural".
92
+ sample_rate: Target sample rate for audio output. Defaults to 24000.
93
+
94
+ Example:
95
+ provider = EdgeTTSProvider()
96
+ session = provider.session(voice="en-GB-SoniaNeural", rate="+10%")
97
+
98
+ async with TTSStream(session, sink=SoundDeviceSink()) as tts:
99
+ await tts.feed("Hello world!")
100
+
101
+ Note:
102
+ Use `edge-tts --list-voices` to see all available voices.
103
+ Voice format: {locale}-{Name}Neural (e.g., en-US-AriaNeural)
104
+ """
105
+
106
+ def __init__(
107
+ self,
108
+ *,
109
+ default_voice: str = "en-US-AriaNeural",
110
+ sample_rate: int = 24000,
111
+ ) -> None:
112
+ self._default_voice = default_voice
113
+ self._sample_rate = sample_rate
114
+
115
+ async def __aenter__(self) -> Self:
116
+ """Enter provider context (no-op for Edge TTS)."""
117
+ return self
118
+
119
+ async def __aexit__(
120
+ self,
121
+ exc_type: type[BaseException] | None,
122
+ exc_val: BaseException | None,
123
+ exc_tb: TracebackType | None,
124
+ ) -> None:
125
+ """Exit provider context (no-op for Edge TTS)."""
126
+
127
+ def session(
128
+ self,
129
+ *,
130
+ voice: str | None = None,
131
+ rate: str = "+0%",
132
+ volume: str = "+0%",
133
+ pitch: str = "+0Hz",
134
+ sample_rate: int | None = None,
135
+ **_: Any,
136
+ ) -> EdgeTTSSession:
137
+ """Create a new Edge TTS session.
138
+
139
+ Args:
140
+ voice: Voice name. Defaults to provider's default voice.
141
+ rate: Speaking rate adjustment (e.g., "+25%", "-10%").
142
+ volume: Volume adjustment (e.g., "+10%", "-20%").
143
+ pitch: Pitch adjustment in Hz (e.g., "+10Hz", "-5Hz").
144
+ sample_rate: Target sample rate. Defaults to provider's sample rate.
145
+
146
+ Returns:
147
+ Configured Edge TTS session.
148
+ """
149
+ return EdgeTTSSession(
150
+ voice=voice or self._default_voice,
151
+ rate=rate,
152
+ volume=volume,
153
+ pitch=pitch,
154
+ sample_rate=sample_rate or self._sample_rate,
155
+ )
@@ -0,0 +1,149 @@
1
+ """OpenAI TTS provider implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, Literal, Self
6
+
7
+ from anyvoice.base import TTSProvider, TTSSession
8
+
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import AsyncIterator
12
+ from types import TracebackType
13
+
14
+ from openai import AsyncOpenAI
15
+
16
+ TTSModel = Literal["tts-1", "tts-1-hd"]
17
+ TTSVoice = Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"]
18
+
19
+
20
+ class OpenAITTSSession(TTSSession):
21
+ """TTS session using OpenAI's streaming API.
22
+
23
+ Args:
24
+ client: OpenAI async client.
25
+ model: TTS model to use.
26
+ voice: Voice for synthesis.
27
+ speed: Speech speed (0.25 to 4.0).
28
+ chunk_size: Size of audio chunks to yield.
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ client: AsyncOpenAI,
34
+ *,
35
+ model: TTSModel = "tts-1",
36
+ voice: TTSVoice = "alloy",
37
+ speed: float = 1.0,
38
+ chunk_size: int = 1024,
39
+ ) -> None:
40
+ self._client = client
41
+ self._model = model
42
+ self._voice = voice
43
+ self._speed = speed
44
+ self._chunk_size = chunk_size
45
+
46
+ async def synthesize(self, text: str) -> AsyncIterator[bytes]:
47
+ """Synthesize text to PCM audio using OpenAI's streaming API.
48
+
49
+ Args:
50
+ text: Text to synthesize.
51
+
52
+ Yields:
53
+ PCM audio chunks (16-bit signed, mono, 24kHz).
54
+ """
55
+ if not text.strip():
56
+ return
57
+
58
+ async with self._client.audio.speech.with_streaming_response.create(
59
+ model=self._model,
60
+ voice=self._voice,
61
+ input=text,
62
+ response_format="pcm",
63
+ speed=self._speed,
64
+ ) as response:
65
+ async for chunk in response.iter_bytes(chunk_size=self._chunk_size):
66
+ yield chunk
67
+
68
+
69
+ class OpenAITTSProvider(TTSProvider):
70
+ """TTS provider using OpenAI's Text-to-Speech API.
71
+
72
+ Provides high-quality neural TTS with streaming support.
73
+ Requires an OpenAI API key.
74
+
75
+ Args:
76
+ api_key: OpenAI API key. If not provided, uses OPENAI_API_KEY env var.
77
+ base_url: Optional custom API base URL.
78
+
79
+ Example:
80
+ provider = OpenAITTSProvider(api_key="sk-...")
81
+ session = provider.session(voice="nova", speed=1.0)
82
+
83
+ async with TTSStream(session, sink=SoundDeviceSink()) as tts:
84
+ await tts.feed("Hello world!")
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ *,
90
+ api_key: str | None = None,
91
+ base_url: str | None = None,
92
+ ) -> None:
93
+ self._api_key = api_key
94
+ self._base_url = base_url
95
+ self._client: AsyncOpenAI | None = None
96
+
97
+ async def __aenter__(self) -> Self:
98
+ """Initialize the OpenAI client."""
99
+ from openai import AsyncOpenAI
100
+
101
+ self._client = AsyncOpenAI(api_key=self._api_key, base_url=self._base_url)
102
+ return self
103
+
104
+ async def __aexit__(
105
+ self,
106
+ exc_type: type[BaseException] | None,
107
+ exc_val: BaseException | None,
108
+ exc_tb: TracebackType | None,
109
+ ) -> None:
110
+ """Close the OpenAI client."""
111
+ if self._client is not None:
112
+ await self._client.close()
113
+ self._client = None
114
+
115
+ def _get_client(self) -> AsyncOpenAI:
116
+ """Get the OpenAI client, initializing lazily if needed."""
117
+ if self._client is None:
118
+ from openai import AsyncOpenAI
119
+
120
+ self._client = AsyncOpenAI(api_key=self._api_key, base_url=self._base_url)
121
+ return self._client
122
+
123
+ def session(
124
+ self,
125
+ *,
126
+ model: TTSModel = "tts-1",
127
+ voice: TTSVoice = "alloy",
128
+ speed: float = 1.0,
129
+ chunk_size: int = 1024,
130
+ **_: Any,
131
+ ) -> OpenAITTSSession:
132
+ """Create a new OpenAI TTS session.
133
+
134
+ Args:
135
+ model: TTS model ("tts-1" for speed, "tts-1-hd" for quality).
136
+ voice: Voice to use (alloy, echo, fable, onyx, nova, shimmer).
137
+ speed: Speech speed from 0.25 to 4.0. Defaults to 1.0.
138
+ chunk_size: Size of audio chunks in bytes. Defaults to 1024.
139
+
140
+ Returns:
141
+ Configured OpenAI TTS session.
142
+ """
143
+ return OpenAITTSSession(
144
+ self._get_client(),
145
+ model=model,
146
+ voice=voice,
147
+ speed=speed,
148
+ chunk_size=chunk_size,
149
+ )
File without changes
@@ -0,0 +1,172 @@
1
+ """Audio sink implementations for TTS output."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from typing import TYPE_CHECKING, Any, Self
7
+
8
+ from anyvoice.base import AudioSink
9
+
10
+
11
+ if TYPE_CHECKING:
12
+ from collections.abc import Awaitable, Callable
13
+ import os
14
+ from types import TracebackType
15
+
16
+
17
+ class SoundDeviceSink(AudioSink):
18
+ """Audio sink that plays PCM audio through the system speakers.
19
+
20
+ Uses sounddevice for real-time audio playback.
21
+
22
+ Args:
23
+ sample_rate: Audio sample rate in Hz. Defaults to 24000.
24
+ channels: Number of audio channels. Defaults to 1 (mono).
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ *,
30
+ sample_rate: int = 24000,
31
+ channels: int = 1,
32
+ ) -> None:
33
+ self._sample_rate = sample_rate
34
+ self._channels = channels
35
+ self._stream: Any = None
36
+
37
+ async def __aenter__(self) -> Self:
38
+ """Start the audio output stream."""
39
+ import sounddevice as sd # type: ignore[import-untyped]
40
+
41
+ self._stream = sd.RawOutputStream(
42
+ samplerate=self._sample_rate,
43
+ channels=self._channels,
44
+ dtype="int16",
45
+ )
46
+ self._stream.start()
47
+ return self
48
+
49
+ async def __aexit__(
50
+ self,
51
+ exc_type: type[BaseException] | None,
52
+ exc_val: BaseException | None,
53
+ exc_tb: TracebackType | None,
54
+ ) -> None:
55
+ """Stop and close the audio output stream."""
56
+ if self._stream is not None:
57
+ self._stream.stop()
58
+ self._stream.close()
59
+ self._stream = None
60
+
61
+ async def write(self, chunk: bytes) -> None:
62
+ """Write audio chunk to the output stream.
63
+
64
+ Args:
65
+ chunk: PCM audio data to play.
66
+ """
67
+ if self._stream is not None and chunk:
68
+ # Run blocking write in executor to not block async loop
69
+ loop = asyncio.get_running_loop()
70
+ await loop.run_in_executor(None, self._stream.write, chunk)
71
+
72
+
73
+ class FileSink(AudioSink):
74
+ """Audio sink that writes PCM audio to a WAV file.
75
+
76
+ Args:
77
+ path: Path to the output WAV file.
78
+ sample_rate: Audio sample rate in Hz. Defaults to 24000.
79
+ channels: Number of audio channels. Defaults to 1 (mono).
80
+ """
81
+
82
+ def __init__(
83
+ self,
84
+ path: str | os.PathLike[str],
85
+ *,
86
+ sample_rate: int = 24000,
87
+ channels: int = 1,
88
+ ) -> None:
89
+ self._path = path
90
+ self._sample_rate = sample_rate
91
+ self._channels = channels
92
+ self._chunks: list[bytes] = []
93
+
94
+ async def __aenter__(self) -> Self:
95
+ """Prepare for receiving audio."""
96
+ self._chunks = []
97
+ return self
98
+
99
+ async def __aexit__(
100
+ self,
101
+ exc_type: type[BaseException] | None,
102
+ exc_val: BaseException | None,
103
+ exc_tb: TracebackType | None,
104
+ ) -> None:
105
+ """Write collected audio to WAV file."""
106
+ import wave
107
+
108
+ if not self._chunks:
109
+ return
110
+
111
+ audio_data = b"".join(self._chunks)
112
+
113
+ with wave.open(str(self._path), "wb") as wf:
114
+ wf.setnchannels(self._channels)
115
+ wf.setsampwidth(2) # 16-bit = 2 bytes
116
+ wf.setframerate(self._sample_rate)
117
+ wf.writeframes(audio_data)
118
+
119
+ self._chunks = []
120
+
121
+ async def write(self, chunk: bytes) -> None:
122
+ """Buffer audio chunk for later writing.
123
+
124
+ Args:
125
+ chunk: PCM audio data to save.
126
+ """
127
+ if chunk:
128
+ self._chunks.append(chunk)
129
+
130
+
131
+ class CallbackSink(AudioSink):
132
+ """Audio sink that passes audio chunks to a user-provided callback.
133
+
134
+ Useful for custom audio processing, streaming, or integration
135
+ with other systems.
136
+
137
+ Args:
138
+ callback: Async or sync callable that receives audio chunks.
139
+ on_close: Optional callback invoked when sink closes.
140
+ """
141
+
142
+ def __init__(
143
+ self,
144
+ callback: Callable[[bytes], Awaitable[None]] | Callable[[bytes], None],
145
+ *,
146
+ on_close: Callable[[], Awaitable[None]] | Callable[[], None] | None = None,
147
+ ) -> None:
148
+ self._callback = callback
149
+ self._on_close = on_close
150
+
151
+ async def __aexit__(
152
+ self,
153
+ exc_type: type[BaseException] | None,
154
+ exc_val: BaseException | None,
155
+ exc_tb: TracebackType | None,
156
+ ) -> None:
157
+ """Invoke close callback if provided."""
158
+ if self._on_close is not None:
159
+ result = self._on_close()
160
+ if asyncio.iscoroutine(result):
161
+ await result
162
+
163
+ async def write(self, chunk: bytes) -> None:
164
+ """Pass audio chunk to the callback.
165
+
166
+ Args:
167
+ chunk: PCM audio data.
168
+ """
169
+ if chunk:
170
+ result = self._callback(chunk)
171
+ if asyncio.iscoroutine(result):
172
+ await result
@@ -0,0 +1,198 @@
1
+ """TTSStream orchestrator for streaming TTS with buffering and modes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ from typing import TYPE_CHECKING, Literal, Self
8
+
9
+ from anyvoice.sinks import SoundDeviceSink
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ from types import TracebackType
14
+
15
+ from anyvoice.base import AudioSink, TTSSession
16
+
17
+ TTSMode = Literal["sync_sentence", "sync_run", "async_queue", "async_cancel"]
18
+ """TTS synchronization modes.
19
+
20
+ - sync_sentence: Wait for each sentence's audio before continuing (slowest, most synchronized)
21
+ - sync_run: Stream fast, wait for all audio at run end (default)
22
+ - async_queue: Stream fast, audio plays in background, multiple runs queue up
23
+ - async_cancel: Stream fast, audio plays in background, new run cancels previous audio
24
+ """
25
+
26
+
27
+ class TTSStream:
28
+ """Orchestrator for streaming TTS with sentence buffering and playback.
29
+
30
+ Coordinates a TTS session with an audio sink, handling:
31
+ - Text buffering and sentence boundary detection
32
+ - Synthesis scheduling (sync vs async modes)
33
+ - Audio playback coordination
34
+
35
+ Args:
36
+ session: TTS session for synthesis.
37
+ sink: Audio sink for output. Defaults to SoundDeviceSink.
38
+ mode: Synchronization mode. Defaults to "sync_run".
39
+ min_text_length: Minimum characters before synthesizing. Defaults to 20.
40
+ sentence_terminators: Characters that end sentences.
41
+
42
+ Example:
43
+ provider = OpenAITTSProvider(api_key="...")
44
+ session = provider.session(voice="nova")
45
+
46
+ async with TTSStream(session) as tts:
47
+ await tts.feed("Hello ")
48
+ await tts.feed("world! ")
49
+ await tts.feed("How are you?")
50
+ # Audio plays and completes before exiting
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ session: TTSSession,
56
+ *,
57
+ sink: AudioSink | None = None,
58
+ mode: TTSMode = "sync_run",
59
+ min_text_length: int = 20,
60
+ sentence_terminators: frozenset[str] | None = None,
61
+ ) -> None:
62
+ self._session = session
63
+ self._sink = sink
64
+ self._mode = mode
65
+ self._min_text_length = min_text_length
66
+ self._sentence_terminators = sentence_terminators or frozenset({".", "!", "?", "\n"})
67
+
68
+ # State
69
+ self._text_buffer = ""
70
+ self._sentence_queue: asyncio.Queue[str | None] = asyncio.Queue()
71
+ self._synthesis_task: asyncio.Task[None] | None = None
72
+ self._active = False
73
+
74
+ async def __aenter__(self) -> Self:
75
+ """Enter the stream context, prepare session and sink."""
76
+ # Initialize sink (default to SoundDeviceSink if not provided)
77
+ if self._sink is None:
78
+ self._sink = SoundDeviceSink()
79
+
80
+ await self._session.__aenter__()
81
+ await self._sink.__aenter__()
82
+ self._active = True
83
+ return self
84
+
85
+ async def __aexit__(
86
+ self,
87
+ exc_type: type[BaseException] | None,
88
+ exc_val: BaseException | None,
89
+ exc_tb: TracebackType | None,
90
+ ) -> None:
91
+ """Exit the stream context, finalize audio and cleanup."""
92
+ try:
93
+ # Process any remaining text in buffer
94
+ if self._text_buffer.strip():
95
+ if self._mode == "sync_sentence":
96
+ await self._synthesize_and_play(self._text_buffer.strip())
97
+ else:
98
+ self._schedule_synthesis(self._text_buffer.strip())
99
+ self._text_buffer = ""
100
+
101
+ # For sync modes, wait for everything to finish
102
+ if self._mode in ("sync_sentence", "sync_run"):
103
+ await self._wait_for_completion()
104
+ finally:
105
+ self._active = False
106
+ await self._session.__aexit__(exc_type, exc_val, exc_tb)
107
+ if self._sink is not None:
108
+ await self._sink.__aexit__(exc_type, exc_val, exc_tb)
109
+
110
+ async def feed(self, text: str) -> None:
111
+ """Feed text to the TTS stream.
112
+
113
+ Text is buffered until sentence boundaries are detected,
114
+ then synthesized according to the configured mode.
115
+
116
+ Args:
117
+ text: Text chunk to add to the stream.
118
+ """
119
+ if not self._active:
120
+ msg = "TTSStream must be used as async context manager"
121
+ raise RuntimeError(msg)
122
+
123
+ self._text_buffer += text
124
+
125
+ # Check for sentence boundaries
126
+ if any(term in self._text_buffer for term in self._sentence_terminators):
127
+ last_term = max(
128
+ (self._text_buffer.rfind(term) for term in self._sentence_terminators),
129
+ default=-1,
130
+ )
131
+
132
+ if last_term > 0 and last_term >= self._min_text_length:
133
+ sentence = self._text_buffer[: last_term + 1].strip()
134
+ self._text_buffer = self._text_buffer[last_term + 1 :]
135
+
136
+ if sentence:
137
+ if self._mode == "sync_sentence":
138
+ await self._synthesize_and_play(sentence)
139
+ else:
140
+ self._schedule_synthesis(sentence)
141
+
142
+ async def cancel(self) -> None:
143
+ """Cancel all pending synthesis and playback."""
144
+ # Cancel synthesis worker
145
+ if self._synthesis_task and not self._synthesis_task.done():
146
+ self._synthesis_task.cancel()
147
+ with contextlib.suppress(asyncio.CancelledError):
148
+ await self._synthesis_task
149
+ self._synthesis_task = None
150
+
151
+ # Clear sentence queue
152
+ while not self._sentence_queue.empty():
153
+ with contextlib.suppress(asyncio.QueueEmpty):
154
+ self._sentence_queue.get_nowait()
155
+
156
+ # Reset text buffer
157
+ self._text_buffer = ""
158
+
159
+ async def _synthesize_and_play(self, text: str) -> None:
160
+ """Synthesize text and play audio synchronously.
161
+
162
+ Args:
163
+ text: Text to synthesize.
164
+ """
165
+ if not text.strip() or self._sink is None:
166
+ return
167
+
168
+ async for chunk in self._session.synthesize(text):
169
+ await self._sink.write(chunk)
170
+
171
+ def _schedule_synthesis(self, text: str) -> None:
172
+ """Queue text for background synthesis.
173
+
174
+ Args:
175
+ text: Text to synthesize.
176
+ """
177
+ # Start worker if not running
178
+ if self._synthesis_task is None or self._synthesis_task.done():
179
+ self._synthesis_task = asyncio.create_task(self._synthesis_worker())
180
+
181
+ # Queue the sentence
182
+ self._sentence_queue.put_nowait(text)
183
+
184
+ async def _synthesis_worker(self) -> None:
185
+ """Background worker that processes sentences from the queue."""
186
+ while True:
187
+ sentence = await self._sentence_queue.get()
188
+ if sentence is None: # Shutdown signal
189
+ break
190
+ await self._synthesize_and_play(sentence)
191
+
192
+ async def _wait_for_completion(self) -> None:
193
+ """Wait for all pending synthesis and playback to complete."""
194
+ if self._synthesis_task and not self._synthesis_task.done():
195
+ # Signal shutdown and wait
196
+ await self._sentence_queue.put(None)
197
+ await self._synthesis_task
198
+ self._synthesis_task = None