lazybird-haystack 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,25 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ matrix:
13
+ include:
14
+ # The oldest supported Haystack and the latest one.
15
+ - python: '3.10'
16
+ haystack: 'haystack-ai==2.12.0'
17
+ - python: '3.13'
18
+ haystack: 'haystack-ai'
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+ - uses: actions/setup-python@v5
22
+ with:
23
+ python-version: ${{ matrix.python }}
24
+ - run: pip install '${{ matrix.haystack }}' -e '.[test]'
25
+ - run: pytest -q
@@ -0,0 +1,21 @@
1
+ # Publishes to PyPI on every version tag (0.1.0, no "v") through PyPI trusted publishing:
2
+ # GitHub's OIDC token signs in, so there is no PyPI token to renew.
3
+ name: Publish
4
+
5
+ on:
6
+ push:
7
+ tags:
8
+ - '*.*.*'
9
+
10
+ jobs:
11
+ publish:
12
+ runs-on: ubuntu-latest
13
+ environment: pypi
14
+ permissions:
15
+ id-token: write
16
+ contents: read
17
+ steps:
18
+ - uses: actions/checkout@v4
19
+ - uses: astral-sh/setup-uv@v6
20
+ - run: uv build
21
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,6 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ .pytest_cache/
6
+ *.mp3
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-03)
4
+
5
+ First release.
6
+
7
+ - `LazybirdTextToSpeech` component: text or SSML in, MP3 `ByteStream` out, with voice, locale, speed and more voice settings, set at initialization or per call. Sync and async.
8
+ - `list_voices` to search your own voices and the Lazybird library.
9
+ - Clear `LazybirdError` messages for an invalid API key, missing credits and other failed requests.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lazybird
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.5
2
+ Name: lazybird-haystack
3
+ Version: 0.1.0
4
+ Summary: Lazybird text to speech for Haystack: natural AI voices (MP3) in your pipelines and agents, 500+ voices in 150+ languages.
5
+ Project-URL: Homepage, https://www.lazybird.app/text-to-speech-api
6
+ Project-URL: Documentation, https://www.lazybird.app/docs/api-reference
7
+ Project-URL: Source, https://github.com/lazybirdai/lazybird-haystack
8
+ Project-URL: Issues, https://github.com/lazybirdai/lazybird-haystack/issues
9
+ Author-email: Lazybird <elyssia@lazybird.app>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: ai-voice,haystack,lazybird,speech,text-to-speech,tts,voiceover
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: haystack-ai>=2.12
19
+ Requires-Dist: httpx
20
+ Provides-Extra: test
21
+ Requires-Dist: pytest; extra == 'test'
22
+ Requires-Dist: pytest-asyncio; extra == 'test'
23
+ Requires-Dist: pytest-httpx; extra == 'test'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # lazybird-haystack
27
+
28
+ [Lazybird](https://www.lazybird.app) text to speech for [Haystack](https://haystack.deepset.ai). The `LazybirdTextToSpeech` component turns text into natural AI speech (MP3) in your pipelines and agents, for voiceovers, spoken answers, announcements and anything else that should talk.
29
+
30
+ Lazybird is an AI voiceover generator with 500+ voices in 150+ languages and accents, voice cloning, voice design and a [text to speech API](https://www.lazybird.app/text-to-speech-api).
31
+
32
+ ## Install
33
+
34
+ ```sh
35
+ pip install lazybird-haystack
36
+ ```
37
+
38
+ Requires Python 3.10 or later and Haystack 2.12 or later.
39
+
40
+ ## Set up your account
41
+
42
+ 1. [Sign up for Lazybird](https://www.lazybird.app). The free plan includes 10,000 credits a month, no credit card needed.
43
+ 2. Open [Studio settings](https://www.lazybird.app/studio/settings) and create an API key.
44
+ 3. Set it as an environment variable:
45
+
46
+ ```sh
47
+ export LAZYBIRD_API_KEY="your-api-key"
48
+ ```
49
+
50
+ ## Usage
51
+
52
+ ### Text to speech
53
+
54
+ ```python
55
+ from lazybird_haystack import LazybirdTextToSpeech
56
+
57
+ tts = LazybirdTextToSpeech()
58
+ result = tts.run(text="Welcome back. Your report is ready.")
59
+ result["audio"].to_file("welcome.mp3")
60
+ ```
61
+
62
+ `run` returns `audio`, a Haystack `ByteStream` with the MP3 and `mime_type` `audio/mpeg`. Text that starts with `<speak>` is sent as SSML, for pauses and pronunciation:
63
+
64
+ ```python
65
+ tts.run(text='<speak>Good morning. <break time="500ms"/> The front door is open.</speak>')
66
+ ```
67
+
68
+ ### Voices, languages and settings
69
+
70
+ ```python
71
+ from lazybird_haystack import LazybirdTextToSpeech, list_voices
72
+
73
+ for voice in list_voices("british narrator")[:5]:
74
+ print(voice["id"], voice["displayName"], voice["language"])
75
+
76
+ tts = LazybirdTextToSpeech(
77
+ voice_id="tgJ2Hes6DauwTg8kFrRPLN", # Elyssia, the default voice
78
+ locale="es-ES", # any voice can speak other languages and accents
79
+ speed=1.1, # 1 is normal (0.5 to 2)
80
+ settings={"pitch": 1.0, "volume": 1.0},
81
+ )
82
+ ```
83
+
84
+ `list_voices` returns your own voices first, then the Lazybird library. `run` also takes `voice_id` and `settings` to override them per call.
85
+
86
+ ### In a pipeline
87
+
88
+ `PromptBuilder` fills in a template and `LazybirdTextToSpeech` speaks it:
89
+
90
+ ```python
91
+ from haystack import Pipeline
92
+ from haystack.components.builders import PromptBuilder
93
+ from lazybird_haystack import LazybirdTextToSpeech
94
+
95
+ pipeline = Pipeline()
96
+ pipeline.add_component("template", PromptBuilder(template="Hi {{ name }}, your order {{ order }} has shipped."))
97
+ pipeline.add_component("tts", LazybirdTextToSpeech())
98
+ pipeline.connect("template.prompt", "tts.text")
99
+
100
+ result = pipeline.run({"template": {"name": "Maya", "order": "1042"}})
101
+ result["tts"]["audio"].to_file("order.mp3")
102
+ ```
103
+
104
+ To load a saved pipeline in Haystack 3, add this package to the trusted modules: `Pipeline.loads(yaml, allowed_modules=["lazybird_haystack"])`.
105
+
106
+ ### Spoken answers from an LLM
107
+
108
+ ```python
109
+ from haystack import Pipeline
110
+ from haystack.components.builders import ChatPromptBuilder
111
+ from haystack.components.converters import OutputAdapter
112
+ from haystack.components.generators.chat import OpenAIChatGenerator
113
+ from haystack.dataclasses import ChatMessage
114
+ from lazybird_haystack import LazybirdTextToSpeech
115
+
116
+ template = [ChatMessage.from_user("Answer in two short sentences: {{ question }}")]
117
+
118
+ pipeline = Pipeline()
119
+ pipeline.add_component("prompt", ChatPromptBuilder(template=template, required_variables=["question"]))
120
+ pipeline.add_component("llm", OpenAIChatGenerator()) # needs OPENAI_API_KEY
121
+ pipeline.add_component("answer", OutputAdapter(template="{{ replies[0].text }}", output_type=str))
122
+ pipeline.add_component("tts", LazybirdTextToSpeech())
123
+ pipeline.connect("prompt.prompt", "llm.messages")
124
+ pipeline.connect("llm.replies", "answer.replies")
125
+ pipeline.connect("answer.output", "tts.text")
126
+
127
+ result = pipeline.run({"prompt": {"question": "Why is the sky blue?"}})
128
+ result["tts"]["audio"].to_file("answer.mp3")
129
+ ```
130
+
131
+ ### Errors
132
+
133
+ An invalid API key, missing credits or another failed request raises `LazybirdError` with a message that says what to fix.
134
+
135
+ ## Pricing
136
+
137
+ One credit is one character of text, shared between the Lazybird studio and the API. The free plan includes 10,000 credits a month; paid plans start at $9 a month and include commercial usage rights. See [pricing](https://www.lazybird.app/pricing).
138
+
139
+ ## Resources
140
+
141
+ - [Lazybird docs](https://www.lazybird.app/docs)
142
+ - [Lazybird API reference](https://www.lazybird.app/docs/api-reference)
143
+ - [Changelog](https://github.com/lazybirdai/lazybird-haystack/blob/main/CHANGELOG.md)
144
+
145
+ ## License
146
+
147
+ [MIT](https://github.com/lazybirdai/lazybird-haystack/blob/main/LICENSE)
@@ -0,0 +1,122 @@
1
+ # lazybird-haystack
2
+
3
+ [Lazybird](https://www.lazybird.app) text to speech for [Haystack](https://haystack.deepset.ai). The `LazybirdTextToSpeech` component turns text into natural AI speech (MP3) in your pipelines and agents, for voiceovers, spoken answers, announcements and anything else that should talk.
4
+
5
+ Lazybird is an AI voiceover generator with 500+ voices in 150+ languages and accents, voice cloning, voice design and a [text to speech API](https://www.lazybird.app/text-to-speech-api).
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pip install lazybird-haystack
11
+ ```
12
+
13
+ Requires Python 3.10 or later and Haystack 2.12 or later.
14
+
15
+ ## Set up your account
16
+
17
+ 1. [Sign up for Lazybird](https://www.lazybird.app). The free plan includes 10,000 credits a month, no credit card needed.
18
+ 2. Open [Studio settings](https://www.lazybird.app/studio/settings) and create an API key.
19
+ 3. Set it as an environment variable:
20
+
21
+ ```sh
22
+ export LAZYBIRD_API_KEY="your-api-key"
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ### Text to speech
28
+
29
+ ```python
30
+ from lazybird_haystack import LazybirdTextToSpeech
31
+
32
+ tts = LazybirdTextToSpeech()
33
+ result = tts.run(text="Welcome back. Your report is ready.")
34
+ result["audio"].to_file("welcome.mp3")
35
+ ```
36
+
37
+ `run` returns `audio`, a Haystack `ByteStream` with the MP3 and `mime_type` `audio/mpeg`. Text that starts with `<speak>` is sent as SSML, for pauses and pronunciation:
38
+
39
+ ```python
40
+ tts.run(text='<speak>Good morning. <break time="500ms"/> The front door is open.</speak>')
41
+ ```
42
+
43
+ ### Voices, languages and settings
44
+
45
+ ```python
46
+ from lazybird_haystack import LazybirdTextToSpeech, list_voices
47
+
48
+ for voice in list_voices("british narrator")[:5]:
49
+ print(voice["id"], voice["displayName"], voice["language"])
50
+
51
+ tts = LazybirdTextToSpeech(
52
+ voice_id="tgJ2Hes6DauwTg8kFrRPLN", # Elyssia, the default voice
53
+ locale="es-ES", # any voice can speak other languages and accents
54
+ speed=1.1, # 1 is normal (0.5 to 2)
55
+ settings={"pitch": 1.0, "volume": 1.0},
56
+ )
57
+ ```
58
+
59
+ `list_voices` returns your own voices first, then the Lazybird library. `run` also takes `voice_id` and `settings` to override them per call.
60
+
61
+ ### In a pipeline
62
+
63
+ `PromptBuilder` fills in a template and `LazybirdTextToSpeech` speaks it:
64
+
65
+ ```python
66
+ from haystack import Pipeline
67
+ from haystack.components.builders import PromptBuilder
68
+ from lazybird_haystack import LazybirdTextToSpeech
69
+
70
+ pipeline = Pipeline()
71
+ pipeline.add_component("template", PromptBuilder(template="Hi {{ name }}, your order {{ order }} has shipped."))
72
+ pipeline.add_component("tts", LazybirdTextToSpeech())
73
+ pipeline.connect("template.prompt", "tts.text")
74
+
75
+ result = pipeline.run({"template": {"name": "Maya", "order": "1042"}})
76
+ result["tts"]["audio"].to_file("order.mp3")
77
+ ```
78
+
79
+ To load a saved pipeline in Haystack 3, add this package to the trusted modules: `Pipeline.loads(yaml, allowed_modules=["lazybird_haystack"])`.
80
+
81
+ ### Spoken answers from an LLM
82
+
83
+ ```python
84
+ from haystack import Pipeline
85
+ from haystack.components.builders import ChatPromptBuilder
86
+ from haystack.components.converters import OutputAdapter
87
+ from haystack.components.generators.chat import OpenAIChatGenerator
88
+ from haystack.dataclasses import ChatMessage
89
+ from lazybird_haystack import LazybirdTextToSpeech
90
+
91
+ template = [ChatMessage.from_user("Answer in two short sentences: {{ question }}")]
92
+
93
+ pipeline = Pipeline()
94
+ pipeline.add_component("prompt", ChatPromptBuilder(template=template, required_variables=["question"]))
95
+ pipeline.add_component("llm", OpenAIChatGenerator()) # needs OPENAI_API_KEY
96
+ pipeline.add_component("answer", OutputAdapter(template="{{ replies[0].text }}", output_type=str))
97
+ pipeline.add_component("tts", LazybirdTextToSpeech())
98
+ pipeline.connect("prompt.prompt", "llm.messages")
99
+ pipeline.connect("llm.replies", "answer.replies")
100
+ pipeline.connect("answer.output", "tts.text")
101
+
102
+ result = pipeline.run({"prompt": {"question": "Why is the sky blue?"}})
103
+ result["tts"]["audio"].to_file("answer.mp3")
104
+ ```
105
+
106
+ ### Errors
107
+
108
+ An invalid API key, missing credits or another failed request raises `LazybirdError` with a message that says what to fix.
109
+
110
+ ## Pricing
111
+
112
+ One credit is one character of text, shared between the Lazybird studio and the API. The free plan includes 10,000 credits a month; paid plans start at $9 a month and include commercial usage rights. See [pricing](https://www.lazybird.app/pricing).
113
+
114
+ ## Resources
115
+
116
+ - [Lazybird docs](https://www.lazybird.app/docs)
117
+ - [Lazybird API reference](https://www.lazybird.app/docs/api-reference)
118
+ - [Changelog](https://github.com/lazybirdai/lazybird-haystack/blob/main/CHANGELOG.md)
119
+
120
+ ## License
121
+
122
+ [MIT](https://github.com/lazybirdai/lazybird-haystack/blob/main/LICENSE)
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "lazybird-haystack"
7
+ version = "0.1.0"
8
+ description = "Lazybird text to speech for Haystack: natural AI voices (MP3) in your pipelines and agents, 500+ voices in 150+ languages."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Lazybird", email = "elyssia@lazybird.app" }]
13
+ requires-python = ">=3.10"
14
+ keywords = ["haystack", "lazybird", "text-to-speech", "tts", "speech", "voiceover", "ai-voice"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Multimedia :: Sound/Audio :: Speech",
20
+ ]
21
+ dependencies = ["haystack-ai>=2.12", "httpx"]
22
+
23
+ [project.optional-dependencies]
24
+ test = ["pytest", "pytest-asyncio", "pytest-httpx"]
25
+
26
+ [project.urls]
27
+ Homepage = "https://www.lazybird.app/text-to-speech-api"
28
+ Documentation = "https://www.lazybird.app/docs/api-reference"
29
+ Source = "https://github.com/lazybirdai/lazybird-haystack"
30
+ Issues = "https://github.com/lazybirdai/lazybird-haystack/issues"
31
+
32
+ [tool.hatch.build.targets.wheel]
33
+ packages = ["src/lazybird_haystack"]
34
+
35
+ [tool.pytest.ini_options]
36
+ asyncio_mode = "auto"
37
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,3 @@
1
+ from lazybird_haystack.text_to_speech import LazybirdError, LazybirdTextToSpeech, list_voices
2
+
3
+ __all__ = ["LazybirdError", "LazybirdTextToSpeech", "list_voices"]
@@ -0,0 +1,174 @@
1
+ import re
2
+ from typing import Any
3
+
4
+ import httpx
5
+ from haystack import component, default_from_dict, default_to_dict
6
+ from haystack.dataclasses import ByteStream
7
+ from haystack.utils import Secret, deserialize_secrets_inplace
8
+
9
+ BASE_URL = "https://api.lazybird.app/v2"
10
+ DEFAULT_VOICE_ID = "tgJ2Hes6DauwTg8kFrRPLN" # Elyssia, a warm narrator
11
+ SSML = re.compile(r"^\s*<speak[\s>]", re.IGNORECASE)
12
+
13
+
14
+ class LazybirdError(Exception):
15
+ """A Lazybird API request failed. The message says what to fix."""
16
+
17
+
18
+ @component
19
+ class LazybirdTextToSpeech:
20
+ """
21
+ Turns text into natural AI speech with [Lazybird](https://www.lazybird.app) and returns the MP3 as a `ByteStream`.
22
+
23
+ Text that starts with `<speak>` is sent as SSML. API reference:
24
+ [lazybird.app/docs/api-reference](https://www.lazybird.app/docs/api-reference).
25
+
26
+ ### Usage example
27
+ ```python
28
+ from lazybird_haystack import LazybirdTextToSpeech
29
+
30
+ tts = LazybirdTextToSpeech() # reads the API key from LAZYBIRD_API_KEY
31
+ result = tts.run(text="Your order has shipped.")
32
+ result["audio"].to_file("order.mp3")
33
+ ```
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ api_key: Secret = Secret.from_env_var("LAZYBIRD_API_KEY"),
39
+ voice_id: str = DEFAULT_VOICE_ID,
40
+ locale: str | None = None,
41
+ speed: float | None = None,
42
+ settings: dict[str, Any] | None = None,
43
+ timeout: float = 120.0,
44
+ ) -> None:
45
+ """
46
+ Creates a LazybirdTextToSpeech component.
47
+
48
+ :param api_key: Your Lazybird API key, from [Studio settings](https://www.lazybird.app/studio/settings).
49
+ :param voice_id: The voice to speak with. Any voice can speak other languages; see `locale`.
50
+ :param locale: Optional language and accent to speak in, such as `es-ES` or `hi-IN`.
51
+ :param speed: Optional speaking speed, 1 is normal (0.5 to 2).
52
+ :param settings: Optional more voice settings: `pitch` (0.5 to 1.5), `volume` (0 to 2), and `style` and
53
+ `styleIntensity` for voices with speaking styles.
54
+ :param timeout: Seconds to wait for the audio.
55
+ """
56
+ self.api_key = api_key
57
+ self.voice_id = voice_id
58
+ self.locale = locale
59
+ self.speed = speed
60
+ self.settings = settings
61
+ self.timeout = timeout
62
+
63
+ @component.output_types(audio=ByteStream)
64
+ def run(self, text: str, voice_id: str | None = None, settings: dict[str, Any] | None = None) -> dict[str, Any]:
65
+ """
66
+ Generates speech for `text`.
67
+
68
+ :param text: The text to speak, or SSML that starts with `<speak>`.
69
+ :param voice_id: If given, overrides the voice set at initialization.
70
+ :param settings: If given, overrides voice settings set at initialization, such as `speed` or `locale`.
71
+ :returns: A dictionary with `audio`, the MP3 as a `ByteStream` with `mime_type` `audio/mpeg`.
72
+ :raises LazybirdError: If the API key is not valid, credits ran out or the request failed.
73
+ """
74
+ body = self._request_body(text, voice_id, settings)
75
+ with httpx.Client(timeout=self.timeout) as client:
76
+ response = client.post(f"{BASE_URL}/generate-speech", headers=self._headers(), json=body)
77
+ return {"audio": _audio(response, body["voiceId"])}
78
+
79
+ @component.output_types(audio=ByteStream)
80
+ async def run_async(
81
+ self, text: str, voice_id: str | None = None, settings: dict[str, Any] | None = None
82
+ ) -> dict[str, Any]:
83
+ """
84
+ Generates speech for `text`. The asynchronous version of `run`, with the same parameters and output.
85
+ """
86
+ body = self._request_body(text, voice_id, settings)
87
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
88
+ response = await client.post(f"{BASE_URL}/generate-speech", headers=self._headers(), json=body)
89
+ return {"audio": _audio(response, body["voiceId"])}
90
+
91
+ def to_dict(self) -> dict[str, Any]:
92
+ """
93
+ Serializes the component to a dictionary.
94
+ """
95
+ return default_to_dict(
96
+ self,
97
+ api_key=self.api_key.to_dict(),
98
+ voice_id=self.voice_id,
99
+ locale=self.locale,
100
+ speed=self.speed,
101
+ settings=self.settings,
102
+ timeout=self.timeout,
103
+ )
104
+
105
+ @classmethod
106
+ def from_dict(cls, data: dict[str, Any]) -> "LazybirdTextToSpeech":
107
+ """
108
+ Deserializes the component from a dictionary.
109
+ """
110
+ deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"])
111
+ return default_from_dict(cls, data)
112
+
113
+ def _headers(self) -> dict[str, str]:
114
+ return {"X-API-Key": self.api_key.resolve_value() or ""}
115
+
116
+ def _request_body(self, text: str, voice_id: str | None, settings: dict[str, Any] | None) -> dict[str, Any]:
117
+ if not isinstance(text, str) or not text.strip():
118
+ raise ValueError("text must be the text (or SSML) to speak.")
119
+ merged = {"locale": self.locale, "speed": self.speed, **(self.settings or {}), **(settings or {})}
120
+ merged = {key: value for key, value in merged.items() if value is not None}
121
+ return {
122
+ "voiceId": voice_id or self.voice_id,
123
+ **({"ssml": text} if SSML.match(text) else {"text": text}),
124
+ **({"settings": merged} if merged else {}),
125
+ }
126
+
127
+
128
+ def list_voices(query: str | None = None, api_key: Secret = Secret.from_env_var("LAZYBIRD_API_KEY")) -> list[dict]:
129
+ """
130
+ Lists voices you can use as `voice_id`: your own voices first, then the Lazybird library.
131
+
132
+ :param query: Optional search by name, language or style, such as `"british narrator"`.
133
+ :param api_key: Your Lazybird API key.
134
+ :returns: Voices as dictionaries with `id`, `displayName`, `language` and `description`.
135
+ """
136
+ params = {"limit": 100, **({"q": query} if query else {})}
137
+ response = httpx.get(
138
+ f"{BASE_URL}/voices", headers={"X-API-Key": api_key.resolve_value() or ""}, params=params, timeout=30
139
+ )
140
+ _raise_for_error(response)
141
+ voices = response.json()
142
+ return [*voices.get("myVoices", []), *voices.get("library", [])]
143
+
144
+
145
+ def _audio(response: httpx.Response, voice_id: str) -> ByteStream:
146
+ _raise_for_error(response)
147
+ return ByteStream(data=response.content, mime_type="audio/mpeg", meta={"voice_id": voice_id})
148
+
149
+
150
+ def _raise_for_error(response: httpx.Response) -> None:
151
+ if response.is_success:
152
+ return
153
+ try:
154
+ body = response.json()
155
+ except ValueError:
156
+ body = {}
157
+ # "Authorization Error: …", "Invalid Input: …" read better without the prefix.
158
+ message = re.sub(r"^[A-Za-z ]+(?:Error|Input): ", "", str(body.get("error") or ""))
159
+ status = response.status_code
160
+ if status == 401:
161
+ raise LazybirdError("Your Lazybird API key is not valid. Check LAZYBIRD_API_KEY.")
162
+ if status == 422:
163
+ if re.search("credit", message, re.IGNORECASE):
164
+ raise LazybirdError(
165
+ "You are out of Lazybird credits. Get more at lazybird.app/pricing, "
166
+ "or wait for your monthly credits to reset."
167
+ )
168
+ raise LazybirdError(f"{message or 'Your plan does not allow this request.'} See lazybird.app/pricing.")
169
+ if status == 429:
170
+ wait = body.get("retryAfterSeconds")
171
+ raise LazybirdError(f"Too many requests. Try again in {wait or 'a few'} seconds.")
172
+ if status == 503:
173
+ raise LazybirdError("Lazybird is busy right now. Try again in a minute.")
174
+ raise LazybirdError(message or f"Lazybird request failed ({status})")
@@ -0,0 +1,131 @@
1
+ import json
2
+
3
+ import pytest
4
+ from haystack import Pipeline
5
+ from haystack.components.builders import PromptBuilder
6
+ from haystack.utils import Secret
7
+
8
+ from lazybird_haystack import LazybirdError, LazybirdTextToSpeech, list_voices
9
+
10
+ MP3 = b"ID3 fake mp3"
11
+ SPEECH_URL = "https://api.lazybird.app/v2/generate-speech"
12
+
13
+
14
+ @pytest.fixture(autouse=True)
15
+ def api_key(monkeypatch):
16
+ monkeypatch.setenv("LAZYBIRD_API_KEY", "test-key")
17
+
18
+
19
+ def sent_body(httpx_mock):
20
+ return json.loads(httpx_mock.get_request().content)
21
+
22
+
23
+ def test_sends_the_text_and_returns_the_mp3(httpx_mock):
24
+ httpx_mock.add_response(url=SPEECH_URL, method="POST", content=MP3, headers={"Content-Type": "audio/mpeg"})
25
+ tts = LazybirdTextToSpeech(voice_id="v1", locale="es-ES", speed=1.2)
26
+
27
+ audio = tts.run(text="Hola")["audio"]
28
+
29
+ assert audio.data == MP3
30
+ assert audio.mime_type == "audio/mpeg"
31
+ assert audio.meta == {"voice_id": "v1"}
32
+ assert httpx_mock.get_request().headers["X-API-Key"] == "test-key"
33
+ assert sent_body(httpx_mock) == {"voiceId": "v1", "text": "Hola", "settings": {"locale": "es-ES", "speed": 1.2}}
34
+
35
+
36
+ def test_sends_ssml_and_takes_overrides_per_call(httpx_mock):
37
+ httpx_mock.add_response(url=SPEECH_URL, content=MP3)
38
+ tts = LazybirdTextToSpeech(speed=1.2, settings={"pitch": 0.9})
39
+
40
+ tts.run(text='<speak>Hi <break time="1s"/> there</speak>', voice_id="v2", settings={"speed": 0.8})
41
+
42
+ assert sent_body(httpx_mock) == {
43
+ "voiceId": "v2",
44
+ "ssml": '<speak>Hi <break time="1s"/> there</speak>',
45
+ "settings": {"speed": 0.8, "pitch": 0.9},
46
+ }
47
+
48
+
49
+ def test_uses_the_default_voice_without_settings(httpx_mock):
50
+ httpx_mock.add_response(url=SPEECH_URL, content=MP3)
51
+
52
+ LazybirdTextToSpeech().run(text="Hello")
53
+
54
+ assert sent_body(httpx_mock) == {"voiceId": "tgJ2Hes6DauwTg8kFrRPLN", "text": "Hello"}
55
+
56
+
57
+ async def test_run_async(httpx_mock):
58
+ httpx_mock.add_response(url=SPEECH_URL, content=MP3)
59
+
60
+ result = await LazybirdTextToSpeech().run_async(text="Hello")
61
+
62
+ assert result["audio"].data == MP3
63
+
64
+
65
+ @pytest.mark.parametrize(
66
+ ("status", "body", "message"),
67
+ [
68
+ (401, {"error": "Authorization Error: bad key"}, "Your Lazybird API key is not valid"),
69
+ (422, {"error": "Insufficient Credits: 0 left"}, "You are out of Lazybird credits"),
70
+ (429, {"error": "Too many requests", "retryAfterSeconds": 30}, "Try again in 30 seconds"),
71
+ (400, {"error": "Invalid Input: Unknown voice"}, "^Unknown voice$"),
72
+ ],
73
+ )
74
+ def test_explains_api_errors(httpx_mock, status, body, message):
75
+ httpx_mock.add_response(url=SPEECH_URL, status_code=status, json=body)
76
+
77
+ with pytest.raises(LazybirdError, match=message):
78
+ LazybirdTextToSpeech().run(text="Hello")
79
+
80
+
81
+ def test_rejects_empty_text_without_calling_the_api(httpx_mock):
82
+ with pytest.raises(ValueError, match="text must be the text"):
83
+ LazybirdTextToSpeech().run(text=" ")
84
+
85
+ assert httpx_mock.get_requests() == []
86
+
87
+
88
+ def test_serializes_without_the_key():
89
+ tts = LazybirdTextToSpeech(voice_id="v1", locale="fr-FR", settings={"volume": 1.5})
90
+
91
+ data = tts.to_dict()
92
+
93
+ assert data == {
94
+ "type": "lazybird_haystack.text_to_speech.LazybirdTextToSpeech",
95
+ "init_parameters": {
96
+ "api_key": {"type": "env_var", "env_vars": ["LAZYBIRD_API_KEY"], "strict": True},
97
+ "voice_id": "v1",
98
+ "locale": "fr-FR",
99
+ "speed": None,
100
+ "settings": {"volume": 1.5},
101
+ "timeout": 120.0,
102
+ },
103
+ }
104
+ restored = LazybirdTextToSpeech.from_dict(data)
105
+ assert restored.voice_id == "v1"
106
+ assert restored.api_key == Secret.from_env_var("LAZYBIRD_API_KEY")
107
+
108
+
109
+ def test_runs_in_a_pipeline_after_a_prompt_builder(httpx_mock, monkeypatch):
110
+ # Haystack 3 loads saved pipelines only from modules the user trusts.
111
+ monkeypatch.setenv("HAYSTACK_DESERIALIZATION_ALLOWLIST", "lazybird_haystack")
112
+ httpx_mock.add_response(url=SPEECH_URL, content=MP3)
113
+ pipeline = Pipeline()
114
+ pipeline.add_component("template", PromptBuilder(template="Hi {{ name }}, your order has shipped."))
115
+ pipeline.add_component("tts", LazybirdTextToSpeech())
116
+ pipeline.connect("template.prompt", "tts.text")
117
+
118
+ result = pipeline.run({"template": {"name": "Maya"}})
119
+
120
+ assert result["tts"]["audio"].data == MP3
121
+ assert sent_body(httpx_mock)["text"] == "Hi Maya, your order has shipped."
122
+ assert Pipeline.loads(pipeline.dumps()).get_component("tts").voice_id == "tgJ2Hes6DauwTg8kFrRPLN"
123
+
124
+
125
+ def test_lists_your_voices_first(httpx_mock):
126
+ httpx_mock.add_response(
127
+ url="https://api.lazybird.app/v2/voices?limit=100&q=warm",
128
+ json={"myVoices": [{"id": "m1", "displayName": "Me"}], "library": [{"id": "l1", "displayName": "Elyssia"}]},
129
+ )
130
+
131
+ assert [voice["id"] for voice in list_voices("warm")] == ["m1", "l1"]