swarmauri_tts_playht 0.11.0.dev4__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.
- swarmauri_tts_playht-0.11.0.dev4/LICENSE +201 -0
- swarmauri_tts_playht-0.11.0.dev4/PKG-INFO +132 -0
- swarmauri_tts_playht-0.11.0.dev4/README.md +102 -0
- swarmauri_tts_playht-0.11.0.dev4/pyproject.toml +69 -0
- swarmauri_tts_playht-0.11.0.dev4/swarmauri_tts_playht/PlayHTModel.py +461 -0
- swarmauri_tts_playht-0.11.0.dev4/swarmauri_tts_playht/__init__.py +10 -0
- swarmauri_tts_playht-0.11.0.dev4/swarmauri_tts_playht/cli.py +197 -0
- swarmauri_tts_playht-0.11.0.dev4/swarmauri_tts_playht/retry.py +105 -0
|
@@ -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 [2025] [Jacob Stewart @ Swarmauri]
|
|
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,132 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: swarmauri_tts_playht
|
|
3
|
+
Version: 0.11.0.dev4
|
|
4
|
+
Summary: Standalone PlayHT text-to-speech provider, stateless agent integration, and CLI for Swarmauri.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: swarmauri,playht,play.ht,text to speech,tts provider,speech synthesis,audio generation,voice cloning,stateless agent,command line interface
|
|
8
|
+
Author: Jacob Stewart
|
|
9
|
+
Author-email: jacob@swarmauri.com
|
|
10
|
+
Requires-Python: >=3.10,<3.13
|
|
11
|
+
Classifier: Development Status :: 1 - Planning
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
23
|
+
Requires-Dist: httpx (>=0.27)
|
|
24
|
+
Requires-Dist: pydantic (>=2.0)
|
|
25
|
+
Requires-Dist: swarmauri_agent_texttospeech
|
|
26
|
+
Requires-Dist: swarmauri_base
|
|
27
|
+
Requires-Dist: swarmauri_core
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+

|
|
31
|
+
|
|
32
|
+
# Swarmauri PlayHT Text-to-Speech
|
|
33
|
+
|
|
34
|
+
`swarmauri_tts_playht` is the standalone PlayHT provider package for Swarmauri.
|
|
35
|
+
Its `PlayHTModel` implements `TTSBase` and converts independent text inputs into
|
|
36
|
+
audio files without pretending to be an LLM.
|
|
37
|
+
|
|
38
|
+
[](https://pepy.tech/projects/swarmauri_tts_playht)
|
|
39
|
+
[](https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_tts_playht/)
|
|
40
|
+
[](https://pypi.org/project/swarmauri_tts_playht/)
|
|
41
|
+
[](https://pypi.org/project/swarmauri_tts_playht/)
|
|
42
|
+
[](https://pypi.org/project/swarmauri_tts_playht/)
|
|
43
|
+
|
|
44
|
+
## Features
|
|
45
|
+
|
|
46
|
+
- Native `TTSBase` provider registered as `swarmauri.tts.PlayHTModel`.
|
|
47
|
+
- Synchronous, asynchronous, and batch audio generation.
|
|
48
|
+
- PlayHT voice discovery and cloned-voice management.
|
|
49
|
+
- Configurable voice engine, voice, output format, and timeout.
|
|
50
|
+
- Agent-only CLI support for positional, piped, file-based, and interactive
|
|
51
|
+
text.
|
|
52
|
+
- Command-line selection of the PlayHT voice model and voice.
|
|
53
|
+
|
|
54
|
+
## Installation
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
uv add swarmauri_tts_playht
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pip install swarmauri_tts_playht
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Set `PLAYHT_API_KEY` and `PLAYHT_USER_ID` before generating audio.
|
|
65
|
+
|
|
66
|
+
## Usage
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
import os
|
|
70
|
+
|
|
71
|
+
from swarmauri_tts_playht import PlayHTModel
|
|
72
|
+
|
|
73
|
+
tts = PlayHTModel(
|
|
74
|
+
api_key=os.environ["PLAYHT_API_KEY"],
|
|
75
|
+
user_id=os.environ["PLAYHT_USER_ID"],
|
|
76
|
+
name="Play3.0-mini",
|
|
77
|
+
voice="Adolfo",
|
|
78
|
+
)
|
|
79
|
+
audio_path = tts.predict("Welcome to Swarmauri.", "welcome.mp3")
|
|
80
|
+
print(audio_path)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Generate through the stateless `TextToSpeechAgent`:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
swarmauri-playht "Welcome to Swarmauri." \
|
|
87
|
+
--voice-model PlayHT2.0-turbo \
|
|
88
|
+
--voice Adolfo \
|
|
89
|
+
--output welcome.mp3
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Every CLI invocation uses `TextToSpeechAgent`. It adds no conversation, memory,
|
|
93
|
+
system context, or text-generating LLM. `--model` remains available as an alias
|
|
94
|
+
for `--voice-model`.
|
|
95
|
+
|
|
96
|
+
The supported command-line voice engines are `Play3.0-mini`,
|
|
97
|
+
`PlayHT2.0-turbo`, `PlayHT1.0`, and `PlayHT2.0`. Text can also come from a UTF-8
|
|
98
|
+
file or standard input:
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
swarmauri-playht --prompt-file announcement.txt --output announcement.mp3
|
|
102
|
+
echo "Welcome to Swarmauri." | swarmauri-playht --output welcome.mp3
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Use the same stateless workflow from Python:
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
import os
|
|
109
|
+
|
|
110
|
+
from swarmauri_agent_texttospeech import TextToSpeechAgent
|
|
111
|
+
from swarmauri_tts_playht import PlayHTModel
|
|
112
|
+
|
|
113
|
+
tts = PlayHTModel(
|
|
114
|
+
api_key=os.environ["PLAYHT_API_KEY"],
|
|
115
|
+
user_id=os.environ["PLAYHT_USER_ID"],
|
|
116
|
+
name="PlayHT2.0-turbo",
|
|
117
|
+
voice="Adolfo",
|
|
118
|
+
)
|
|
119
|
+
agent = TextToSpeechAgent(tts=tts, output_path="welcome.mp3")
|
|
120
|
+
audio_path = agent.exec("Welcome to Swarmauri.")
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Contributing
|
|
124
|
+
|
|
125
|
+
This package is part of the
|
|
126
|
+
[Swarmauri SDK](https://github.com/swarmauri/swarmauri-sdk). Contributions
|
|
127
|
+
should follow the repository contribution and style guides.
|
|
128
|
+
|
|
129
|
+
## License
|
|
130
|
+
|
|
131
|
+
Apache-2.0
|
|
132
|
+
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
# Swarmauri PlayHT Text-to-Speech
|
|
4
|
+
|
|
5
|
+
`swarmauri_tts_playht` is the standalone PlayHT provider package for Swarmauri.
|
|
6
|
+
Its `PlayHTModel` implements `TTSBase` and converts independent text inputs into
|
|
7
|
+
audio files without pretending to be an LLM.
|
|
8
|
+
|
|
9
|
+
[](https://pepy.tech/projects/swarmauri_tts_playht)
|
|
10
|
+
[](https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_tts_playht/)
|
|
11
|
+
[](https://pypi.org/project/swarmauri_tts_playht/)
|
|
12
|
+
[](https://pypi.org/project/swarmauri_tts_playht/)
|
|
13
|
+
[](https://pypi.org/project/swarmauri_tts_playht/)
|
|
14
|
+
|
|
15
|
+
## Features
|
|
16
|
+
|
|
17
|
+
- Native `TTSBase` provider registered as `swarmauri.tts.PlayHTModel`.
|
|
18
|
+
- Synchronous, asynchronous, and batch audio generation.
|
|
19
|
+
- PlayHT voice discovery and cloned-voice management.
|
|
20
|
+
- Configurable voice engine, voice, output format, and timeout.
|
|
21
|
+
- Agent-only CLI support for positional, piped, file-based, and interactive
|
|
22
|
+
text.
|
|
23
|
+
- Command-line selection of the PlayHT voice model and voice.
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
uv add swarmauri_tts_playht
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install swarmauri_tts_playht
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Set `PLAYHT_API_KEY` and `PLAYHT_USER_ID` before generating audio.
|
|
36
|
+
|
|
37
|
+
## Usage
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import os
|
|
41
|
+
|
|
42
|
+
from swarmauri_tts_playht import PlayHTModel
|
|
43
|
+
|
|
44
|
+
tts = PlayHTModel(
|
|
45
|
+
api_key=os.environ["PLAYHT_API_KEY"],
|
|
46
|
+
user_id=os.environ["PLAYHT_USER_ID"],
|
|
47
|
+
name="Play3.0-mini",
|
|
48
|
+
voice="Adolfo",
|
|
49
|
+
)
|
|
50
|
+
audio_path = tts.predict("Welcome to Swarmauri.", "welcome.mp3")
|
|
51
|
+
print(audio_path)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Generate through the stateless `TextToSpeechAgent`:
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
swarmauri-playht "Welcome to Swarmauri." \
|
|
58
|
+
--voice-model PlayHT2.0-turbo \
|
|
59
|
+
--voice Adolfo \
|
|
60
|
+
--output welcome.mp3
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Every CLI invocation uses `TextToSpeechAgent`. It adds no conversation, memory,
|
|
64
|
+
system context, or text-generating LLM. `--model` remains available as an alias
|
|
65
|
+
for `--voice-model`.
|
|
66
|
+
|
|
67
|
+
The supported command-line voice engines are `Play3.0-mini`,
|
|
68
|
+
`PlayHT2.0-turbo`, `PlayHT1.0`, and `PlayHT2.0`. Text can also come from a UTF-8
|
|
69
|
+
file or standard input:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
swarmauri-playht --prompt-file announcement.txt --output announcement.mp3
|
|
73
|
+
echo "Welcome to Swarmauri." | swarmauri-playht --output welcome.mp3
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Use the same stateless workflow from Python:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
import os
|
|
80
|
+
|
|
81
|
+
from swarmauri_agent_texttospeech import TextToSpeechAgent
|
|
82
|
+
from swarmauri_tts_playht import PlayHTModel
|
|
83
|
+
|
|
84
|
+
tts = PlayHTModel(
|
|
85
|
+
api_key=os.environ["PLAYHT_API_KEY"],
|
|
86
|
+
user_id=os.environ["PLAYHT_USER_ID"],
|
|
87
|
+
name="PlayHT2.0-turbo",
|
|
88
|
+
voice="Adolfo",
|
|
89
|
+
)
|
|
90
|
+
agent = TextToSpeechAgent(tts=tts, output_path="welcome.mp3")
|
|
91
|
+
audio_path = agent.exec("Welcome to Swarmauri.")
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Contributing
|
|
95
|
+
|
|
96
|
+
This package is part of the
|
|
97
|
+
[Swarmauri SDK](https://github.com/swarmauri/swarmauri-sdk). Contributions
|
|
98
|
+
should follow the repository contribution and style guides.
|
|
99
|
+
|
|
100
|
+
## License
|
|
101
|
+
|
|
102
|
+
Apache-2.0
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "swarmauri_tts_playht"
|
|
3
|
+
version = "0.11.0.dev4"
|
|
4
|
+
description = "Standalone PlayHT text-to-speech provider, stateless agent integration, and CLI for Swarmauri."
|
|
5
|
+
license = "Apache-2.0"
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
repository = "https://github.com/swarmauri/swarmauri-sdk"
|
|
8
|
+
requires-python = ">=3.10,<3.13"
|
|
9
|
+
classifiers = [
|
|
10
|
+
"Development Status :: 1 - Planning",
|
|
11
|
+
"Intended Audience :: Developers",
|
|
12
|
+
"License :: OSI Approved :: Apache Software License",
|
|
13
|
+
"Operating System :: OS Independent",
|
|
14
|
+
"Programming Language :: Python",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
17
|
+
"Programming Language :: Python :: 3.10",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Topic :: Multimedia :: Sound/Audio :: Speech",
|
|
21
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
22
|
+
]
|
|
23
|
+
authors = [{ name = "Jacob Stewart", email = "jacob@swarmauri.com" }]
|
|
24
|
+
dependencies = [
|
|
25
|
+
"httpx>=0.27",
|
|
26
|
+
"pydantic>=2.0",
|
|
27
|
+
"swarmauri_core",
|
|
28
|
+
"swarmauri_base",
|
|
29
|
+
"swarmauri_agent_texttospeech",
|
|
30
|
+
]
|
|
31
|
+
keywords = [
|
|
32
|
+
"swarmauri",
|
|
33
|
+
"playht",
|
|
34
|
+
"play.ht",
|
|
35
|
+
"text to speech",
|
|
36
|
+
"tts provider",
|
|
37
|
+
"speech synthesis",
|
|
38
|
+
"audio generation",
|
|
39
|
+
"voice cloning",
|
|
40
|
+
"stateless agent",
|
|
41
|
+
"command line interface",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
[tool.uv.sources]
|
|
45
|
+
swarmauri_core = { workspace = true }
|
|
46
|
+
swarmauri_base = { workspace = true }
|
|
47
|
+
swarmauri_agent_texttospeech = { workspace = true }
|
|
48
|
+
|
|
49
|
+
[project.entry-points.'swarmauri.tts']
|
|
50
|
+
PlayHTModel = "swarmauri_tts_playht:PlayHTModel"
|
|
51
|
+
|
|
52
|
+
[project.scripts]
|
|
53
|
+
swarmauri-playht = "swarmauri_tts_playht.cli:main"
|
|
54
|
+
|
|
55
|
+
[tool.pytest.ini_options]
|
|
56
|
+
markers = ["unit: Unit tests"]
|
|
57
|
+
asyncio_mode = "auto"
|
|
58
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
59
|
+
|
|
60
|
+
[build-system]
|
|
61
|
+
requires = ["poetry-core>=1.0.0"]
|
|
62
|
+
build-backend = "poetry.core.masonry.api"
|
|
63
|
+
|
|
64
|
+
[dependency-groups]
|
|
65
|
+
dev = [
|
|
66
|
+
"pytest>=8.0",
|
|
67
|
+
"pytest-asyncio>=0.24.0",
|
|
68
|
+
"ruff>=0.9.9",
|
|
69
|
+
]
|
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
from typing import Dict, List, Literal
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
from pydantic import Field, PrivateAttr, SecretStr
|
|
8
|
+
from swarmauri_base.tts.TTSBase import TTSBase
|
|
9
|
+
from swarmauri_base.ComponentBase import ComponentBase
|
|
10
|
+
|
|
11
|
+
from .retry import retry_on_status_codes
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@ComponentBase.register_type(TTSBase, "PlayHTModel")
|
|
15
|
+
class PlayHTModel(TTSBase):
|
|
16
|
+
"""
|
|
17
|
+
A class for Play.ht text-to-speech (TTS) synthesis using various voice
|
|
18
|
+
models.
|
|
19
|
+
|
|
20
|
+
This class interacts with the Play.ht API to synthesize text to speech,
|
|
21
|
+
clone voices, and manage voice operations (like getting, cloning, and
|
|
22
|
+
deleting).
|
|
23
|
+
Attributes:
|
|
24
|
+
allowed_models (List[str]): List of TTS models supported by Play.ht,
|
|
25
|
+
such as "Play3.0-mini" and "PlayHT2.0".
|
|
26
|
+
allowed_voices (List[str]): List of voice names available for the
|
|
27
|
+
selected model.
|
|
28
|
+
voice (str): The selected voice name for synthesis (default: "Adolfo").
|
|
29
|
+
api_key (str): API key for authenticating with Play.ht's API.
|
|
30
|
+
user_id (str): User ID for authenticating with Play.ht's API.
|
|
31
|
+
name (str): Name of the TTS model to use (default: "Play3.0-mini").
|
|
32
|
+
type (Literal["PlayHTModel"]): Fixed component type.
|
|
33
|
+
output_format (str): Format of the output audio file, e.g., "mp3".
|
|
34
|
+
|
|
35
|
+
Provider resourses: https://docs.play.ht/reference/api-getting-started
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
allowed_models: List[str] = [
|
|
39
|
+
"PlayDialog",
|
|
40
|
+
"Play3.0-mini",
|
|
41
|
+
"PlayHT2.0-turbo",
|
|
42
|
+
"PlayHT1.0",
|
|
43
|
+
"PlayHT2.0",
|
|
44
|
+
]
|
|
45
|
+
allowed_voices: List[str] = Field(default=None)
|
|
46
|
+
voice: str = Field(default="Adolfo")
|
|
47
|
+
api_key: SecretStr
|
|
48
|
+
user_id: str
|
|
49
|
+
name: str = "Play3.0-mini"
|
|
50
|
+
type: Literal["PlayHTModel"] = "PlayHTModel"
|
|
51
|
+
output_format: str = "mp3"
|
|
52
|
+
timeout: float = 600.0
|
|
53
|
+
_voice_id: str = PrivateAttr(default=None)
|
|
54
|
+
_prebuilt_voices: Dict[
|
|
55
|
+
Literal["Play3.0-mini", "PlayHT2.0-turbo", "PlayHT1.0", "PlayHT2.0"],
|
|
56
|
+
List[dict],
|
|
57
|
+
] = PrivateAttr(default=None)
|
|
58
|
+
_BASE_URL: str = PrivateAttr(default="https://api.play.ht/api/v2")
|
|
59
|
+
_headers: Dict[str, str] = PrivateAttr(default=None)
|
|
60
|
+
|
|
61
|
+
def __init__(self, **data) -> None:
|
|
62
|
+
"""
|
|
63
|
+
Initialize the PlayHTModel with API credentials and voice settings.
|
|
64
|
+
"""
|
|
65
|
+
super().__init__(**data)
|
|
66
|
+
self._headers = {
|
|
67
|
+
"accept": "audio/mpeg",
|
|
68
|
+
"content-type": "application/json",
|
|
69
|
+
"AUTHORIZATION": self.api_key.get_secret_value(),
|
|
70
|
+
"X-USER-ID": self.user_id,
|
|
71
|
+
}
|
|
72
|
+
if not self.allowed_models:
|
|
73
|
+
self.allowed_models = self.get_allowed_models()
|
|
74
|
+
self.__prebuilt_voices = self._fetch_prebuilt_voices()
|
|
75
|
+
self.allowed_voices = self._get_allowed_voices(self.name)
|
|
76
|
+
self._validate_voice_in_allowed_voices()
|
|
77
|
+
|
|
78
|
+
def _validate_voice_in_allowed_voices(self) -> None:
|
|
79
|
+
"""
|
|
80
|
+
Validate the voice name against the allowed voices for the model.
|
|
81
|
+
"""
|
|
82
|
+
voice = self.voice
|
|
83
|
+
model = self.name
|
|
84
|
+
|
|
85
|
+
if model not in self.allowed_models:
|
|
86
|
+
raise ValueError(
|
|
87
|
+
(
|
|
88
|
+
f"{model} voice engine not allowed. Choose from "
|
|
89
|
+
f"{self.allowed_models}"
|
|
90
|
+
)
|
|
91
|
+
)
|
|
92
|
+
if voice and voice not in self.allowed_voices:
|
|
93
|
+
raise ValueError(
|
|
94
|
+
(
|
|
95
|
+
f"Voice name {voice} is not allowed for this {model} voice " # noqa: E501
|
|
96
|
+
f"engine. Choose from {self.allowed_voices}"
|
|
97
|
+
)
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
@retry_on_status_codes((429, 529), max_retries=1)
|
|
101
|
+
def _fetch_prebuilt_voices(self) -> Dict[str, List[str]]:
|
|
102
|
+
"""
|
|
103
|
+
Fetch prebuilt voices for each allowed model from the Play.ht API.
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
dict: Dictionary mapping models to lists of voice dictionaries.
|
|
107
|
+
"""
|
|
108
|
+
prebuilt_voices = {}
|
|
109
|
+
|
|
110
|
+
self._headers["accept"] = "application/json"
|
|
111
|
+
|
|
112
|
+
with httpx.Client(
|
|
113
|
+
base_url=self._BASE_URL, timeout=self.timeout
|
|
114
|
+
) as client:
|
|
115
|
+
voice_response = client.get("/voices", headers=self._headers)
|
|
116
|
+
voice_response.raise_for_status()
|
|
117
|
+
|
|
118
|
+
for item in json.loads(voice_response.text):
|
|
119
|
+
voice_engine = item.get("voice_engine")
|
|
120
|
+
if voice_engine not in self.allowed_models:
|
|
121
|
+
continue
|
|
122
|
+
if voice_engine not in prebuilt_voices:
|
|
123
|
+
prebuilt_voices[voice_engine] = []
|
|
124
|
+
prebuilt_voices[voice_engine].append(
|
|
125
|
+
{item.get("id"): item.get("name")}
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
cloned_voice_response = self.get_cloned_voices()
|
|
129
|
+
if isinstance(cloned_voice_response, list):
|
|
130
|
+
prebuilt_voices.setdefault("PlayHT2.0", [])
|
|
131
|
+
for item in cloned_voice_response:
|
|
132
|
+
prebuilt_voices["PlayHT2.0"].append(
|
|
133
|
+
{item.get("id"): item.get("name")}
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
return prebuilt_voices
|
|
137
|
+
|
|
138
|
+
def _get_allowed_voices(self, model: str) -> List[str]:
|
|
139
|
+
"""
|
|
140
|
+
Retrieve allowed voices for a specified model.
|
|
141
|
+
|
|
142
|
+
Parameters:
|
|
143
|
+
model (str): The model name to retrieve voices for.
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
list: List of allowed voice names.
|
|
147
|
+
"""
|
|
148
|
+
allowed_voices = []
|
|
149
|
+
|
|
150
|
+
if model in self.allowed_models:
|
|
151
|
+
for item in self.__prebuilt_voices.get(model, []):
|
|
152
|
+
allowed_voices.append(*item.values())
|
|
153
|
+
if model != "PlayHT2.0":
|
|
154
|
+
allowed_voices.extend(self._get_allowed_voices("PlayHT2.0"))
|
|
155
|
+
return allowed_voices
|
|
156
|
+
|
|
157
|
+
def _get_voice_id(self, voice_name: str) -> str:
|
|
158
|
+
"""
|
|
159
|
+
Retrieve the voice ID associated with a given voice name.
|
|
160
|
+
|
|
161
|
+
Parameters:
|
|
162
|
+
voice_name (str): The name of the voice to retrieve the ID for.
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
str: Voice ID for the specified voice name.
|
|
166
|
+
"""
|
|
167
|
+
if self.name in self.allowed_models:
|
|
168
|
+
voices = list(self.__prebuilt_voices.get(self.name, []))
|
|
169
|
+
if self.name != "PlayHT2.0":
|
|
170
|
+
voices.extend(self.__prebuilt_voices.get("PlayHT2.0", []))
|
|
171
|
+
for item in voices:
|
|
172
|
+
if voice_name in item.values():
|
|
173
|
+
return list(item.keys())[0]
|
|
174
|
+
|
|
175
|
+
raise ValueError(
|
|
176
|
+
f"Voice name {voice_name} not found in allowed voices."
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
@retry_on_status_codes((429, 529), max_retries=1)
|
|
180
|
+
def predict(self, text: str, audio_path: str = "output.mp3") -> str:
|
|
181
|
+
"""
|
|
182
|
+
Convert text to speech using Play.ht's API and save as an audio file.
|
|
183
|
+
|
|
184
|
+
Parameters:
|
|
185
|
+
text (str): The text to convert to speech.
|
|
186
|
+
audio_path (str): Path to save the synthesized audio.
|
|
187
|
+
Returns:
|
|
188
|
+
str: Absolute path to the saved audio file.
|
|
189
|
+
"""
|
|
190
|
+
payload = {
|
|
191
|
+
"voice": self._get_voice_id(self.voice),
|
|
192
|
+
"output_format": self.output_format,
|
|
193
|
+
"voice_engine": self.name,
|
|
194
|
+
"text": text,
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
try:
|
|
198
|
+
headers = {**self._headers, "accept": "audio/mpeg"}
|
|
199
|
+
with httpx.Client(
|
|
200
|
+
base_url=self._BASE_URL, timeout=self.timeout
|
|
201
|
+
) as self._client:
|
|
202
|
+
response = self._client.post(
|
|
203
|
+
"/tts/stream", json=payload, headers=headers
|
|
204
|
+
)
|
|
205
|
+
response.raise_for_status()
|
|
206
|
+
|
|
207
|
+
with open(audio_path, "wb") as f:
|
|
208
|
+
f.write(response.content)
|
|
209
|
+
|
|
210
|
+
return os.path.abspath(audio_path)
|
|
211
|
+
except Exception as e:
|
|
212
|
+
raise RuntimeError(f"Text-to-Speech synthesis failed: {e}")
|
|
213
|
+
|
|
214
|
+
@retry_on_status_codes((429, 529), max_retries=1)
|
|
215
|
+
async def apredict(self, text: str, audio_path: str = "output.mp3") -> str:
|
|
216
|
+
"""
|
|
217
|
+
Asynchronously convert text to speech and save it as an audio file.
|
|
218
|
+
|
|
219
|
+
Parameters:
|
|
220
|
+
text (str): Text to convert to speech.
|
|
221
|
+
audio_path (str): Path to save the synthesized audio file.
|
|
222
|
+
|
|
223
|
+
Returns:
|
|
224
|
+
str: Path to the saved audio file.
|
|
225
|
+
"""
|
|
226
|
+
payload = {
|
|
227
|
+
"voice": self._get_voice_id(self.voice),
|
|
228
|
+
"output_format": self.output_format,
|
|
229
|
+
"voice_engine": self.name,
|
|
230
|
+
"text": text,
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
try:
|
|
234
|
+
headers = {**self._headers, "accept": "audio/mpeg"}
|
|
235
|
+
async with httpx.AsyncClient(
|
|
236
|
+
base_url=self._BASE_URL, timeout=self.timeout
|
|
237
|
+
) as async_client:
|
|
238
|
+
response = await async_client.post(
|
|
239
|
+
"/tts/stream", json=payload, headers=headers
|
|
240
|
+
)
|
|
241
|
+
response.raise_for_status()
|
|
242
|
+
with open(audio_path, "wb") as f:
|
|
243
|
+
f.write(response.content)
|
|
244
|
+
return os.path.abspath(audio_path)
|
|
245
|
+
except Exception as e:
|
|
246
|
+
raise RuntimeError(f"Text-to-Speech synthesis failed: {e}")
|
|
247
|
+
|
|
248
|
+
def batch(self, text_path_dict: Dict[str, str]) -> List:
|
|
249
|
+
"""
|
|
250
|
+
Process multiple text-to-speech conversions synchronously.
|
|
251
|
+
|
|
252
|
+
Parameters:
|
|
253
|
+
text_path_dict (Dict[str, str]): Dictionary of text and
|
|
254
|
+
corresponding audio paths.
|
|
255
|
+
Returns:
|
|
256
|
+
List: List of audio file paths.
|
|
257
|
+
"""
|
|
258
|
+
return [
|
|
259
|
+
self.predict(text, path) for text, path in text_path_dict.items()
|
|
260
|
+
]
|
|
261
|
+
|
|
262
|
+
async def abatch(
|
|
263
|
+
self, text_path_dict: Dict[str, str], max_concurrent: int = 5
|
|
264
|
+
) -> List["str"]:
|
|
265
|
+
"""
|
|
266
|
+
Process multiple text-to-speech conversions asynchronously with
|
|
267
|
+
controlled concurrency.
|
|
268
|
+
|
|
269
|
+
Parameters:
|
|
270
|
+
text_path_dict (Dict[str, str]): Dictionary of text and
|
|
271
|
+
corresponding audio paths.
|
|
272
|
+
max_concurrent (int): Maximum number of concurrent tasks.
|
|
273
|
+
Returns:
|
|
274
|
+
List: List of audio file paths.
|
|
275
|
+
"""
|
|
276
|
+
semaphore = asyncio.Semaphore(max_concurrent)
|
|
277
|
+
|
|
278
|
+
async def process_text(text, path) -> str:
|
|
279
|
+
async with semaphore:
|
|
280
|
+
return await self.apredict(text, path)
|
|
281
|
+
|
|
282
|
+
tasks = [
|
|
283
|
+
process_text(text, path) for text, path in text_path_dict.items()
|
|
284
|
+
]
|
|
285
|
+
return await asyncio.gather(*tasks)
|
|
286
|
+
|
|
287
|
+
def clone_voice_from_file(
|
|
288
|
+
self, voice_name: str, sample_file_path: str
|
|
289
|
+
) -> dict:
|
|
290
|
+
"""
|
|
291
|
+
Clone a voice using an audio file.
|
|
292
|
+
|
|
293
|
+
Parameters:
|
|
294
|
+
voice_name (str): The name for the cloned voice.
|
|
295
|
+
sample_file_path (str): Path to the sample audio file.
|
|
296
|
+
|
|
297
|
+
Returns:
|
|
298
|
+
dict: Response from the Play.ht API.
|
|
299
|
+
"""
|
|
300
|
+
payload = {"voice_name": voice_name}
|
|
301
|
+
self._headers["accept"] = "application/json"
|
|
302
|
+
|
|
303
|
+
try:
|
|
304
|
+
with open(sample_file_path, "rb") as sample_file:
|
|
305
|
+
files = {
|
|
306
|
+
"sample_file": (
|
|
307
|
+
os.path.basename(sample_file_path),
|
|
308
|
+
sample_file,
|
|
309
|
+
"audio/mp4",
|
|
310
|
+
)
|
|
311
|
+
}
|
|
312
|
+
with httpx.Client(
|
|
313
|
+
base_url=self._BASE_URL, timeout=self.timeout
|
|
314
|
+
) as client:
|
|
315
|
+
response = client.post(
|
|
316
|
+
"/cloned-voices/instant",
|
|
317
|
+
data=payload,
|
|
318
|
+
files=files,
|
|
319
|
+
headers=self._headers,
|
|
320
|
+
)
|
|
321
|
+
response.raise_for_status()
|
|
322
|
+
|
|
323
|
+
return response.json()
|
|
324
|
+
except httpx.RequestError as e:
|
|
325
|
+
print(f"An error occurred while cloning the voice: {e}")
|
|
326
|
+
return {"error": str(e)}
|
|
327
|
+
|
|
328
|
+
def clone_voice_from_url(
|
|
329
|
+
self, voice_name: str, sample_file_url: str
|
|
330
|
+
) -> dict:
|
|
331
|
+
"""
|
|
332
|
+
Clone a voice by sending a URL to an audio file to Play.ht API.
|
|
333
|
+
|
|
334
|
+
:param voice_name: The name for the cloned voice.
|
|
335
|
+
:param sample_file_url: The URL to the audio file to be used for
|
|
336
|
+
cloning the voice.
|
|
337
|
+
:return: A dictionary containing the response from the Play.ht API.
|
|
338
|
+
"""
|
|
339
|
+
# Constructing the payload with the sample file URL
|
|
340
|
+
boundary = "-----011000010111000001101001"
|
|
341
|
+
payload = (
|
|
342
|
+
f"{boundary}\r\n"
|
|
343
|
+
'Content-Disposition: form-data; name="sample_file_url"\r\n\r\n'
|
|
344
|
+
f"{sample_file_url}\r\n"
|
|
345
|
+
f'{boundary}--; name="voice_name"\r\n\r\n'
|
|
346
|
+
f"{voice_name}\r\n"
|
|
347
|
+
f"{boundary}--"
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
self._headers["content-type"] = (
|
|
351
|
+
"multipart/form-data; boundary=---011000010111000001101001"
|
|
352
|
+
)
|
|
353
|
+
self._headers["accept"] = "application/json"
|
|
354
|
+
|
|
355
|
+
try:
|
|
356
|
+
with httpx.Client(
|
|
357
|
+
base_url=self._BASE_URL, timeout=self.timeout
|
|
358
|
+
) as client:
|
|
359
|
+
response = client.post(
|
|
360
|
+
"/cloned-voices/instant",
|
|
361
|
+
data=payload,
|
|
362
|
+
headers=self._headers,
|
|
363
|
+
)
|
|
364
|
+
response.raise_for_status()
|
|
365
|
+
|
|
366
|
+
return response.json()
|
|
367
|
+
|
|
368
|
+
except httpx.RequestError as e:
|
|
369
|
+
print(f"An error occurred while cloning the voice: {e}")
|
|
370
|
+
return {"error": str(e)}
|
|
371
|
+
|
|
372
|
+
def delete_cloned_voice(self, voice_id: str) -> dict:
|
|
373
|
+
"""
|
|
374
|
+
Delete a cloned voice using its voice_id from Play.ht.
|
|
375
|
+
|
|
376
|
+
:param voice_id: The ID of the cloned voice to delete.
|
|
377
|
+
:return: A dictionary containing the response from the Play.ht API.
|
|
378
|
+
"""
|
|
379
|
+
|
|
380
|
+
payload = {"voice_id": voice_id}
|
|
381
|
+
self._headers["accept"] = "application/json"
|
|
382
|
+
|
|
383
|
+
try:
|
|
384
|
+
with httpx.Client(
|
|
385
|
+
base_url=self._BASE_URL, timeout=self.timeout
|
|
386
|
+
) as client:
|
|
387
|
+
response = client.delete(
|
|
388
|
+
"/cloned-voices", json=payload, headers=self._headers
|
|
389
|
+
)
|
|
390
|
+
response.raise_for_status()
|
|
391
|
+
|
|
392
|
+
return response.json()
|
|
393
|
+
|
|
394
|
+
except httpx.RequestError as e:
|
|
395
|
+
print(f"An error occurred while deleting the cloned voice: {e}")
|
|
396
|
+
return {"error": str(e)}
|
|
397
|
+
|
|
398
|
+
def get_cloned_voices(self) -> dict:
|
|
399
|
+
"""
|
|
400
|
+
Get a list of cloned voices from Play.ht.
|
|
401
|
+
|
|
402
|
+
:return: A dictionary containing the cloned voices or an error message.
|
|
403
|
+
"""
|
|
404
|
+
self._headers["accept"] = "application/json"
|
|
405
|
+
|
|
406
|
+
try:
|
|
407
|
+
with httpx.Client(
|
|
408
|
+
base_url=self._BASE_URL, timeout=self.timeout
|
|
409
|
+
) as client:
|
|
410
|
+
response = client.get("/cloned-voices", headers=self._headers)
|
|
411
|
+
response.raise_for_status()
|
|
412
|
+
|
|
413
|
+
return response.json()
|
|
414
|
+
|
|
415
|
+
except httpx.RequestError as e:
|
|
416
|
+
print(f"An error occurred while retrieving cloned voices: {e}")
|
|
417
|
+
return {"error": str(e)}
|
|
418
|
+
|
|
419
|
+
def get_allowed_models(self) -> List[str]:
|
|
420
|
+
"""
|
|
421
|
+
Queries the LLMProvider API endpoint to retrieve the list of allowed
|
|
422
|
+
models.
|
|
423
|
+
|
|
424
|
+
Returns:
|
|
425
|
+
List[str]: List of allowed model names.
|
|
426
|
+
"""
|
|
427
|
+
models_data = [
|
|
428
|
+
"Play3.0-mini",
|
|
429
|
+
"PlayHT2.0-turbo",
|
|
430
|
+
"PlayHT1.0",
|
|
431
|
+
"PlayHT2.0",
|
|
432
|
+
]
|
|
433
|
+
return models_data
|
|
434
|
+
|
|
435
|
+
def stream(self, text: str) -> bytes:
|
|
436
|
+
"""
|
|
437
|
+
Stream TTS audio using httpx.
|
|
438
|
+
|
|
439
|
+
Parameters:
|
|
440
|
+
text (str): The text to convert to speech.
|
|
441
|
+
|
|
442
|
+
Returns:
|
|
443
|
+
bytes: bytes of the audio.
|
|
444
|
+
"""
|
|
445
|
+
raise NotImplementedError(
|
|
446
|
+
"Stream method not implemented for PlayHTModel"
|
|
447
|
+
)
|
|
448
|
+
|
|
449
|
+
async def astream(self, text: str) -> bytes:
|
|
450
|
+
"""
|
|
451
|
+
Asynchronously stream TTS audio using httpx.
|
|
452
|
+
|
|
453
|
+
Parameters:
|
|
454
|
+
text (str): The text to convert to speech.
|
|
455
|
+
|
|
456
|
+
Returns:
|
|
457
|
+
bytes: bytes of the audio.
|
|
458
|
+
"""
|
|
459
|
+
raise NotImplementedError(
|
|
460
|
+
"AStream method not implemented for PlayHTModel"
|
|
461
|
+
)
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Generate speech from a user prompt with PlayHT."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Callable, Iterable
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, TextIO
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
DEFAULT_MODEL = "Play3.0-mini"
|
|
14
|
+
DEFAULT_OUTPUT = "output.mp3"
|
|
15
|
+
DEFAULT_VOICE = "Adolfo"
|
|
16
|
+
PLAYHT_MODELS = (
|
|
17
|
+
"Play3.0-mini",
|
|
18
|
+
"PlayHT2.0-turbo",
|
|
19
|
+
"PlayHT1.0",
|
|
20
|
+
"PlayHT2.0",
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
25
|
+
"""Build the PlayHT command-line parser."""
|
|
26
|
+
parser = argparse.ArgumentParser(
|
|
27
|
+
prog="swarmauri-playht",
|
|
28
|
+
description="Generate an audio file from text with PlayHT.",
|
|
29
|
+
)
|
|
30
|
+
parser.add_argument(
|
|
31
|
+
"prompt",
|
|
32
|
+
nargs="?",
|
|
33
|
+
help="Text to speak; omit to read piped input or prompt interactively",
|
|
34
|
+
)
|
|
35
|
+
parser.add_argument(
|
|
36
|
+
"-f",
|
|
37
|
+
"--prompt-file",
|
|
38
|
+
type=Path,
|
|
39
|
+
help="Read the text to speak from a UTF-8 file",
|
|
40
|
+
)
|
|
41
|
+
parser.add_argument(
|
|
42
|
+
"-o",
|
|
43
|
+
"--output",
|
|
44
|
+
type=Path,
|
|
45
|
+
default=Path(DEFAULT_OUTPUT),
|
|
46
|
+
help=f"Audio output path (default: {DEFAULT_OUTPUT})",
|
|
47
|
+
)
|
|
48
|
+
parser.add_argument(
|
|
49
|
+
"--voice",
|
|
50
|
+
default=DEFAULT_VOICE,
|
|
51
|
+
help=f"PlayHT voice name (default: {DEFAULT_VOICE})",
|
|
52
|
+
)
|
|
53
|
+
parser.add_argument(
|
|
54
|
+
"--voice-model",
|
|
55
|
+
"--model",
|
|
56
|
+
dest="voice_model",
|
|
57
|
+
choices=PLAYHT_MODELS,
|
|
58
|
+
default=DEFAULT_MODEL,
|
|
59
|
+
help=f"PlayHT voice engine (default: {DEFAULT_MODEL})",
|
|
60
|
+
)
|
|
61
|
+
parser.add_argument(
|
|
62
|
+
"--api-key",
|
|
63
|
+
help="PlayHT API key (prefer the PLAYHT_API_KEY environment variable)",
|
|
64
|
+
)
|
|
65
|
+
parser.add_argument(
|
|
66
|
+
"--user-id",
|
|
67
|
+
help="PlayHT user ID (prefer the PLAYHT_USER_ID environment variable)",
|
|
68
|
+
)
|
|
69
|
+
parser.add_argument(
|
|
70
|
+
"--timeout",
|
|
71
|
+
type=float,
|
|
72
|
+
default=600.0,
|
|
73
|
+
help="Provider request timeout in seconds (default: 600)",
|
|
74
|
+
)
|
|
75
|
+
return parser
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def read_prompt(
|
|
79
|
+
args: argparse.Namespace,
|
|
80
|
+
input_stream: TextIO,
|
|
81
|
+
input_func: Callable[[str], str],
|
|
82
|
+
) -> str:
|
|
83
|
+
"""Read and validate prompt text from the selected input source."""
|
|
84
|
+
if args.prompt is not None and args.prompt_file is not None:
|
|
85
|
+
raise ValueError("Use either PROMPT or --prompt-file, not both.")
|
|
86
|
+
|
|
87
|
+
if args.prompt_file is not None:
|
|
88
|
+
try:
|
|
89
|
+
prompt = args.prompt_file.read_text(encoding="utf-8")
|
|
90
|
+
except OSError as exc:
|
|
91
|
+
raise ValueError(
|
|
92
|
+
f"Could not read prompt file '{args.prompt_file}': {exc}"
|
|
93
|
+
) from exc
|
|
94
|
+
elif args.prompt is not None:
|
|
95
|
+
prompt = args.prompt
|
|
96
|
+
elif not input_stream.isatty():
|
|
97
|
+
prompt = input_stream.read()
|
|
98
|
+
else:
|
|
99
|
+
prompt = input_func("Text to synthesize: ")
|
|
100
|
+
|
|
101
|
+
prompt = prompt.strip()
|
|
102
|
+
if not prompt:
|
|
103
|
+
raise ValueError("The prompt cannot be empty.")
|
|
104
|
+
return prompt
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def resolve_credentials(args: argparse.Namespace) -> tuple[str, str]:
|
|
108
|
+
"""Resolve PlayHT credentials from flags or environment variables."""
|
|
109
|
+
api_key = args.api_key or os.getenv("PLAYHT_API_KEY")
|
|
110
|
+
user_id = args.user_id or os.getenv("PLAYHT_USER_ID")
|
|
111
|
+
|
|
112
|
+
missing = []
|
|
113
|
+
if not api_key:
|
|
114
|
+
missing.append("PLAYHT_API_KEY")
|
|
115
|
+
if not user_id:
|
|
116
|
+
missing.append("PLAYHT_USER_ID")
|
|
117
|
+
if missing:
|
|
118
|
+
names = " and ".join(missing)
|
|
119
|
+
raise ValueError(f"Missing PlayHT credentials: set {names}.")
|
|
120
|
+
|
|
121
|
+
return api_key, user_id
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def generate_audio(
|
|
125
|
+
args: argparse.Namespace,
|
|
126
|
+
prompt: str,
|
|
127
|
+
tts_factory: Callable[..., Any] | None = None,
|
|
128
|
+
agent_factory: Callable[..., Any] | None = None,
|
|
129
|
+
) -> Path:
|
|
130
|
+
"""Generate an audio file and return its absolute path."""
|
|
131
|
+
if args.timeout <= 0:
|
|
132
|
+
raise ValueError("--timeout must be greater than zero.")
|
|
133
|
+
|
|
134
|
+
api_key, user_id = resolve_credentials(args)
|
|
135
|
+
if tts_factory is None:
|
|
136
|
+
from .PlayHTModel import PlayHTModel
|
|
137
|
+
|
|
138
|
+
tts_factory = PlayHTModel
|
|
139
|
+
|
|
140
|
+
output = args.output.expanduser().resolve()
|
|
141
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
142
|
+
tts = tts_factory(
|
|
143
|
+
api_key=api_key,
|
|
144
|
+
user_id=user_id,
|
|
145
|
+
name=args.voice_model,
|
|
146
|
+
voice=args.voice,
|
|
147
|
+
timeout=args.timeout,
|
|
148
|
+
)
|
|
149
|
+
if agent_factory is None:
|
|
150
|
+
from swarmauri_agent_texttospeech import TextToSpeechAgent
|
|
151
|
+
|
|
152
|
+
agent_factory = TextToSpeechAgent
|
|
153
|
+
agent = agent_factory(tts=tts, output_path=str(output))
|
|
154
|
+
return Path(agent.exec(prompt))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def main(
|
|
158
|
+
argv: Iterable[str] | None = None,
|
|
159
|
+
*,
|
|
160
|
+
input_stream: TextIO | None = None,
|
|
161
|
+
output_stream: TextIO | None = None,
|
|
162
|
+
error_stream: TextIO | None = None,
|
|
163
|
+
input_func: Callable[[str], str] = input,
|
|
164
|
+
tts_factory: Callable[..., Any] | None = None,
|
|
165
|
+
agent_factory: Callable[..., Any] | None = None,
|
|
166
|
+
) -> int:
|
|
167
|
+
"""Run the PlayHT audio-generation command."""
|
|
168
|
+
parser = build_parser()
|
|
169
|
+
args = parser.parse_args(list(argv) if argv is not None else None)
|
|
170
|
+
input_stream = input_stream or sys.stdin
|
|
171
|
+
output_stream = output_stream or sys.stdout
|
|
172
|
+
error_stream = error_stream or sys.stderr
|
|
173
|
+
|
|
174
|
+
try:
|
|
175
|
+
prompt = read_prompt(args, input_stream, input_func)
|
|
176
|
+
audio_path = generate_audio(
|
|
177
|
+
args,
|
|
178
|
+
prompt,
|
|
179
|
+
tts_factory=tts_factory,
|
|
180
|
+
agent_factory=agent_factory,
|
|
181
|
+
)
|
|
182
|
+
except KeyboardInterrupt:
|
|
183
|
+
print("Audio generation cancelled.", file=error_stream)
|
|
184
|
+
return 130
|
|
185
|
+
except ValueError as exc:
|
|
186
|
+
print(f"Error: {exc}", file=error_stream)
|
|
187
|
+
return 2
|
|
188
|
+
except Exception as exc:
|
|
189
|
+
print(f"PlayHT audio generation failed: {exc}", file=error_stream)
|
|
190
|
+
return 1
|
|
191
|
+
|
|
192
|
+
print(f"Audio saved to {audio_path}", file=output_stream)
|
|
193
|
+
return 0
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
if __name__ == "__main__":
|
|
197
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import logging
|
|
3
|
+
import httpx
|
|
4
|
+
from functools import wraps
|
|
5
|
+
from typing import List, Callable, Any
|
|
6
|
+
import asyncio
|
|
7
|
+
import inspect
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def retry_on_status_codes(
|
|
11
|
+
status_codes: List[int] = [429], max_retries: int = 3, retry_delay: int = 2
|
|
12
|
+
):
|
|
13
|
+
"""
|
|
14
|
+
A decorator to retry both sync and async functions when specific status
|
|
15
|
+
codes are encountered,
|
|
16
|
+
with exponential backoff.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
20
|
+
@wraps(func)
|
|
21
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
22
|
+
last_exception = None
|
|
23
|
+
attempt = 0
|
|
24
|
+
while attempt < max_retries:
|
|
25
|
+
try:
|
|
26
|
+
return await func(*args, **kwargs)
|
|
27
|
+
except httpx.HTTPStatusError as e:
|
|
28
|
+
if e.response.status_code in status_codes:
|
|
29
|
+
attempt += 1
|
|
30
|
+
last_exception = e
|
|
31
|
+
if attempt == max_retries:
|
|
32
|
+
break
|
|
33
|
+
backoff_time = retry_delay * (2 ** (attempt - 1))
|
|
34
|
+
logging.warning(
|
|
35
|
+
f"Retry attempt {attempt}/{max_retries}: "
|
|
36
|
+
f"Received HTTP {e.response.status_code} for "
|
|
37
|
+
f"{func.__name__}. "
|
|
38
|
+
f"Retrying in {backoff_time:.2f} seconds. "
|
|
39
|
+
f"Original error: {str(e)}"
|
|
40
|
+
)
|
|
41
|
+
await asyncio.sleep(backoff_time)
|
|
42
|
+
else:
|
|
43
|
+
raise
|
|
44
|
+
|
|
45
|
+
if last_exception:
|
|
46
|
+
error_message = (
|
|
47
|
+
f"Request to {func.__name__} failed after {max_retries} "
|
|
48
|
+
f"retries. "
|
|
49
|
+
f"Last encountered status code: "
|
|
50
|
+
f"{last_exception.response.status_code}. "
|
|
51
|
+
f"Last error details: {str(last_exception)}"
|
|
52
|
+
)
|
|
53
|
+
logging.error(error_message)
|
|
54
|
+
raise Exception(error_message)
|
|
55
|
+
raise RuntimeError(
|
|
56
|
+
f"Unexpected error in retry mechanism for {func.__name__}"
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
@wraps(func)
|
|
60
|
+
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
61
|
+
last_exception = None
|
|
62
|
+
attempt = 0
|
|
63
|
+
while attempt < max_retries:
|
|
64
|
+
try:
|
|
65
|
+
return func(*args, **kwargs)
|
|
66
|
+
except httpx.HTTPStatusError as e:
|
|
67
|
+
if e.response.status_code in status_codes:
|
|
68
|
+
attempt += 1
|
|
69
|
+
last_exception = e
|
|
70
|
+
if attempt == max_retries:
|
|
71
|
+
break
|
|
72
|
+
backoff_time = retry_delay * (2 ** (attempt - 1))
|
|
73
|
+
logging.warning(
|
|
74
|
+
f"Retry attempt {attempt}/{max_retries}: "
|
|
75
|
+
f"Received HTTP {e.response.status_code} for "
|
|
76
|
+
f"{func.__name__}. "
|
|
77
|
+
f"Retrying in {backoff_time:.2f} seconds. "
|
|
78
|
+
f"Original error: {str(e)}"
|
|
79
|
+
)
|
|
80
|
+
time.sleep(backoff_time)
|
|
81
|
+
else:
|
|
82
|
+
raise
|
|
83
|
+
|
|
84
|
+
if last_exception:
|
|
85
|
+
error_message = (
|
|
86
|
+
f"Request to {func.__name__} failed after {max_retries} "
|
|
87
|
+
f"retries. "
|
|
88
|
+
f"Last encountered status code: "
|
|
89
|
+
f"{last_exception.response.status_code}. "
|
|
90
|
+
f"Last error details: {str(last_exception)}"
|
|
91
|
+
)
|
|
92
|
+
logging.error(error_message)
|
|
93
|
+
raise Exception(error_message)
|
|
94
|
+
raise RuntimeError(
|
|
95
|
+
f"Unexpected error in retry mechanism for {func.__name__}"
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
# Check if the function is async or sync and return appropriate wrapper
|
|
99
|
+
return (
|
|
100
|
+
async_wrapper
|
|
101
|
+
if inspect.iscoroutinefunction(func)
|
|
102
|
+
else sync_wrapper
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
return decorator
|