lazybird-haystack 0.1.0__py3-none-any.whl
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,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,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,6 @@
|
|
|
1
|
+
lazybird_haystack/__init__.py,sha256=LTEtYexgRNFxgHzpf459G2b-Yfc538IzsPD0_g7O5d0,162
|
|
2
|
+
lazybird_haystack/text_to_speech.py,sha256=_THRgwK7N9qRt-oj-p83tgjIf7DkFjtl7iQx2v7s2L0,7504
|
|
3
|
+
lazybird_haystack-0.1.0.dist-info/METADATA,sha256=mlhnv7ARNUdixJHIgOh0-S-w3fd8b6DlVJ_Oi75HVGY,5683
|
|
4
|
+
lazybird_haystack-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
5
|
+
lazybird_haystack-0.1.0.dist-info/licenses/LICENSE,sha256=ZYuAb_0GjXxcx8R_eJSJ7HxX3NByml19q0lffOFrbgA,1065
|
|
6
|
+
lazybird_haystack-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|