tts-api-client 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.
- tts_api_client/__init__.py +4 -0
- tts_api_client/client.py +137 -0
- tts_api_client-0.1.0.dist-info/METADATA +92 -0
- tts_api_client-0.1.0.dist-info/RECORD +7 -0
- tts_api_client-0.1.0.dist-info/WHEEL +5 -0
- tts_api_client-0.1.0.dist-info/licenses/LICENSE +21 -0
- tts_api_client-0.1.0.dist-info/top_level.txt +1 -0
tts_api_client/client.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""HTTP-клиент для TTS API (https://github.com/<ты>/tts-api)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
|
|
9
|
+
__all__ = ["TTS_API", "TTSError"]
|
|
10
|
+
|
|
11
|
+
DEFAULT_API_URL = "http://84.21.173.179:3000/tts"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class TTSError(Exception):
|
|
15
|
+
"""Ошибка при обращении к TTS API.
|
|
16
|
+
|
|
17
|
+
Атрибуты:
|
|
18
|
+
kind: короткий код ошибки — ``tts_down``, ``tts_invalid``, ``tts_limit``.
|
|
19
|
+
message: человекочитаемое описание.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, kind: str, message: str) -> None:
|
|
23
|
+
self.kind = kind
|
|
24
|
+
self.message = message
|
|
25
|
+
super().__init__(message)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _json_err(resp: requests.Response) -> str:
|
|
29
|
+
try:
|
|
30
|
+
return resp.json().get("error", resp.text)
|
|
31
|
+
except ValueError:
|
|
32
|
+
return resp.text
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class TTS_API:
|
|
36
|
+
"""Клиент TTS API.
|
|
37
|
+
|
|
38
|
+
Пример:
|
|
39
|
+
>>> from tts_api_client import TTS_API
|
|
40
|
+
>>> api = TTS_API("tts_xxx")
|
|
41
|
+
>>> api.get_voice("Привет", voice="male")
|
|
42
|
+
'C:/path/voice_message.mp3'
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
token: str,
|
|
48
|
+
api_url: str = DEFAULT_API_URL,
|
|
49
|
+
user_agent: str = "tts_api_client/1.0",
|
|
50
|
+
timeout: int = 30,
|
|
51
|
+
) -> None:
|
|
52
|
+
if not token:
|
|
53
|
+
raise ValueError("token не должен быть пустым")
|
|
54
|
+
|
|
55
|
+
self.token = token
|
|
56
|
+
self.api_url = api_url
|
|
57
|
+
self.timeout = timeout
|
|
58
|
+
self._session = requests.Session()
|
|
59
|
+
self._session.headers.update({"User-Agent": user_agent})
|
|
60
|
+
|
|
61
|
+
def get_voice(
|
|
62
|
+
self,
|
|
63
|
+
text: str,
|
|
64
|
+
lang: str = "ru",
|
|
65
|
+
out_path: Optional[str] = None,
|
|
66
|
+
save_dir: Optional[str] = None,
|
|
67
|
+
filename: str = "voice_message.mp3",
|
|
68
|
+
voice: str = "female",
|
|
69
|
+
timeout: Optional[int] = None,
|
|
70
|
+
) -> str:
|
|
71
|
+
"""Синтезирует текст в MP3 и сохраняет файл.
|
|
72
|
+
|
|
73
|
+
Приоритет путей:
|
|
74
|
+
1. ``out_path`` — полный путь к файлу (папка создаётся).
|
|
75
|
+
2. ``save_dir`` — папка + ``filename``.
|
|
76
|
+
3. ничего — текущая рабочая папка + ``filename``.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
text: Текст для озвучки (до 200 символов).
|
|
80
|
+
lang: Язык, по умолчанию ``ru``.
|
|
81
|
+
out_path: Полный путь к итоговому MP3.
|
|
82
|
+
save_dir: Папка для сохранения.
|
|
83
|
+
filename: Имя файла, если задан ``save_dir``.
|
|
84
|
+
voice: ``female`` (по умолчанию) или ``male``.
|
|
85
|
+
timeout: Таймаут запроса в секундах (переопределяет значение из конструктора).
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
Абсолютный путь к сохранённому файлу.
|
|
89
|
+
|
|
90
|
+
Raises:
|
|
91
|
+
TTSError: при ошибке сети или ответа API.
|
|
92
|
+
"""
|
|
93
|
+
# 1. Определяем итоговый путь
|
|
94
|
+
if out_path:
|
|
95
|
+
final_path = os.path.abspath(out_path)
|
|
96
|
+
elif save_dir:
|
|
97
|
+
final_path = os.path.abspath(os.path.join(save_dir, filename))
|
|
98
|
+
else:
|
|
99
|
+
final_path = os.path.abspath(os.path.join(os.getcwd(), filename))
|
|
100
|
+
|
|
101
|
+
os.makedirs(os.path.dirname(final_path) or ".", exist_ok=True)
|
|
102
|
+
|
|
103
|
+
# 2. Запрос
|
|
104
|
+
params = {
|
|
105
|
+
"text": text,
|
|
106
|
+
"lang": lang,
|
|
107
|
+
"token": self.token,
|
|
108
|
+
"voice": voice,
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
try:
|
|
112
|
+
resp = self._session.get(
|
|
113
|
+
self.api_url,
|
|
114
|
+
params=params,
|
|
115
|
+
timeout=timeout or self.timeout,
|
|
116
|
+
)
|
|
117
|
+
except requests.RequestException as exc:
|
|
118
|
+
raise TTSError("tts_down", f"сеть: {exc}") from exc
|
|
119
|
+
|
|
120
|
+
# 3. Обработка статусов
|
|
121
|
+
if resp.status_code in (401, 403):
|
|
122
|
+
raise TTSError("tts_invalid", _json_err(resp))
|
|
123
|
+
if resp.status_code == 429:
|
|
124
|
+
raise TTSError("tts_limit", _json_err(resp))
|
|
125
|
+
if resp.status_code >= 500:
|
|
126
|
+
raise TTSError("tts_down", _json_err(resp))
|
|
127
|
+
if resp.status_code != 200:
|
|
128
|
+
raise TTSError("tts_invalid", f"{resp.status_code}: {_json_err(resp)}")
|
|
129
|
+
|
|
130
|
+
if "audio" not in resp.headers.get("Content-Type", ""):
|
|
131
|
+
raise TTSError("tts_invalid", "ожидался audio/*")
|
|
132
|
+
|
|
133
|
+
# 4. Сохранение
|
|
134
|
+
with open(final_path, "wb") as f:
|
|
135
|
+
f.write(resp.content)
|
|
136
|
+
|
|
137
|
+
return final_path
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tts-api-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Клиент для собственного TTS API (Edge TTS / Google Translate TTS)
|
|
5
|
+
Author-email: Denis Bisekeev <bisekeevdenis@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/<ты>/tts-api-client
|
|
8
|
+
Project-URL: Source, https://github.com/<ты>/tts-api-client
|
|
9
|
+
Project-URL: Issues, https://github.com/<ты>/tts-api-client/issues
|
|
10
|
+
Keywords: tts,text-to-speech,audio,mp3,voice
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
20
|
+
Classifier: Operating System :: OS Independent
|
|
21
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
|
|
22
|
+
Requires-Python: >=3.8
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: requests>=2.25
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# tts-api-client
|
|
29
|
+
|
|
30
|
+
Python-клиент для [TTS API](https://github.com/<ты>/tts-api) — синтез речи в MP3,
|
|
31
|
+
выбор мужского/женского голоса, сохранение в любую папку.
|
|
32
|
+
|
|
33
|
+
## Установка
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install tts-api-client
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Быстрый старт
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from tts_api_client import TTS_API
|
|
43
|
+
|
|
44
|
+
api = TTS_API("tts_xxxxxxxxxxxxxxxxxxxxxxxx")
|
|
45
|
+
|
|
46
|
+
# Сохранит в текущую папку → ./voice_message.mp3
|
|
47
|
+
path = api.get_voice("Привет, мир!")
|
|
48
|
+
print(path)
|
|
49
|
+
|
|
50
|
+
# Мужской голос + своя папка
|
|
51
|
+
api.get_voice("Привет", voice="male", save_dir="cache", filename="hi.mp3")
|
|
52
|
+
|
|
53
|
+
# Полный путь
|
|
54
|
+
api.get_voice("Привет", out_path="/tmp/hello.mp3")
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## API
|
|
58
|
+
|
|
59
|
+
### `TTS_API(token, api_url=DEFAULT_API_URL, user_agent="tts_api_client/1.0", timeout=30)`
|
|
60
|
+
|
|
61
|
+
Создаёт клиент. Токен получается на лендинге твоего TTS API (`POST /api/register`).
|
|
62
|
+
|
|
63
|
+
### `TTS_API.get_voice(...)`
|
|
64
|
+
|
|
65
|
+
| Параметр | Тип | По умолчанию | Описание |
|
|
66
|
+
|------------|----------------|------------------------|-----------------------------------|
|
|
67
|
+
| `text` | `str` | — | Текст, до 200 символов |
|
|
68
|
+
| `lang` | `str` | `"ru"` | Язык |
|
|
69
|
+
| `out_path` | `Optional[str]`| `None` | Полный путь к файлу |
|
|
70
|
+
| `save_dir` | `Optional[str]`| `None` | Папка (с `filename`) |
|
|
71
|
+
| `filename` | `str` | `"voice_message.mp3"` | Имя файла |
|
|
72
|
+
| `voice` | `str` | `"female"` | `female` или `male` |
|
|
73
|
+
| `timeout` | `Optional[int]`| `None` | Таймаут (переопределяет дефолт) |
|
|
74
|
+
|
|
75
|
+
Возвращает **абсолютный путь** к сохранённому MP3.
|
|
76
|
+
|
|
77
|
+
### `TTSError`
|
|
78
|
+
|
|
79
|
+
Ловится отдельно. Поле `kind` — `tts_down`, `tts_invalid` или `tts_limit`.
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from tts_api_client import TTS_API, TTSError
|
|
83
|
+
|
|
84
|
+
try:
|
|
85
|
+
TTS_API("tts_xxx").get_voice("Привет")
|
|
86
|
+
except TTSError as e:
|
|
87
|
+
print(e.kind, e.message)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Лицензия
|
|
91
|
+
|
|
92
|
+
MIT
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
tts_api_client/__init__.py,sha256=02-gw0iB3lkd5t74NBlHNKqmByMjmu8qHvB3Ufj5XZA,133
|
|
2
|
+
tts_api_client/client.py,sha256=EyT40VIWeRK4hkFYICHmERpTZxb79ooI_lPy-0Ex0_M,4757
|
|
3
|
+
tts_api_client-0.1.0.dist-info/licenses/LICENSE,sha256=ZBZDZRs9aEQD2isjVMOeBib9jTogtAVUU0mDp-yIhYM,1090
|
|
4
|
+
tts_api_client-0.1.0.dist-info/METADATA,sha256=BLYo-wzl7qDkhBCK0OMvJH8EoNNIp_JkQxtLBuQCiJ4,3620
|
|
5
|
+
tts_api_client-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
tts_api_client-0.1.0.dist-info/top_level.txt,sha256=Ynp9q86znpF-xpZqfrLryLA8sryPs9zcRB5WPmv1x5I,15
|
|
7
|
+
tts_api_client-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Denis Bisekeev
|
|
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 @@
|
|
|
1
|
+
tts_api_client
|