nexusapi-sdk 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.
- nexusapi_sdk-0.1.0/LICENSE +21 -0
- nexusapi_sdk-0.1.0/PKG-INFO +187 -0
- nexusapi_sdk-0.1.0/README.md +135 -0
- nexusapi_sdk-0.1.0/nexusapi/__init__.py +43 -0
- nexusapi_sdk-0.1.0/nexusapi/client.py +302 -0
- nexusapi_sdk-0.1.0/nexusapi/errors.py +47 -0
- nexusapi_sdk-0.1.0/nexusapi_sdk.egg-info/PKG-INFO +187 -0
- nexusapi_sdk-0.1.0/nexusapi_sdk.egg-info/SOURCES.txt +11 -0
- nexusapi_sdk-0.1.0/nexusapi_sdk.egg-info/dependency_links.txt +1 -0
- nexusapi_sdk-0.1.0/nexusapi_sdk.egg-info/requires.txt +1 -0
- nexusapi_sdk-0.1.0/nexusapi_sdk.egg-info/top_level.txt +1 -0
- nexusapi_sdk-0.1.0/pyproject.toml +45 -0
- nexusapi_sdk-0.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 NexusAPI
|
|
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,187 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: nexusapi-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK для NexusAPI — генерация видео и изображений через единый API (Veo, Kling, Seedance, Nano-Banana)
|
|
5
|
+
Author-email: NexusAPI <support@nexusapi.dev>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2026 NexusAPI
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://nexusapi.dev
|
|
29
|
+
Project-URL: Documentation, https://docs.nexusapi.dev
|
|
30
|
+
Project-URL: Repository, https://github.com/EmilJaf/main-api-v1
|
|
31
|
+
Project-URL: Issues, https://github.com/EmilJaf/main-api-v1/issues
|
|
32
|
+
Keywords: ai,video,image,generation,veo,kling,seedance,nano-banana,sora,openai-compatible,idempotency-key
|
|
33
|
+
Classifier: Development Status :: 4 - Beta
|
|
34
|
+
Classifier: Intended Audience :: Developers
|
|
35
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
36
|
+
Classifier: Operating System :: OS Independent
|
|
37
|
+
Classifier: Programming Language :: Python :: 3
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
42
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
43
|
+
Classifier: Topic :: Multimedia :: Graphics
|
|
44
|
+
Classifier: Topic :: Multimedia :: Video
|
|
45
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
46
|
+
Classifier: Typing :: Typed
|
|
47
|
+
Requires-Python: >=3.9
|
|
48
|
+
Description-Content-Type: text/markdown
|
|
49
|
+
License-File: LICENSE
|
|
50
|
+
Requires-Dist: httpx>=0.24
|
|
51
|
+
Dynamic: license-file
|
|
52
|
+
|
|
53
|
+
# NexusAPI Python SDK
|
|
54
|
+
|
|
55
|
+
Официальный Python SDK для [NexusAPI](https://nexusapi.dev) — единый API для
|
|
56
|
+
генерации видео и изображений через Veo, Kling, Seedance, Nano-Banana и др.
|
|
57
|
+
|
|
58
|
+
## Установка
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pip install nexusapi-sdk
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
> Пакет на PyPI называется `nexusapi-sdk` (имя `nexusapi` зарезервировано
|
|
65
|
+
> похожим проектом). Импорт остаётся `from nexusapi import ...`.
|
|
66
|
+
|
|
67
|
+
## Quickstart
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from nexusapi import NexusClient
|
|
71
|
+
|
|
72
|
+
client = NexusClient(api_key="ВАШ_КЛЮЧ") # создать в panel.nexusapi.dev
|
|
73
|
+
|
|
74
|
+
# Изображение (sync — SDK сам опрашивает статус)
|
|
75
|
+
img = client.images.generate(
|
|
76
|
+
model="nano-banana",
|
|
77
|
+
prompt="Минималистичный логотип кофейни",
|
|
78
|
+
aspect_ratio="1:1",
|
|
79
|
+
)
|
|
80
|
+
print(img.image_url)
|
|
81
|
+
# → https://nexusapi-s3.../result.png
|
|
82
|
+
|
|
83
|
+
# Видео (async — получаем Task, ждём отдельно)
|
|
84
|
+
task = client.videos.create(
|
|
85
|
+
model="veo-3-fast",
|
|
86
|
+
prompt="Кот играет на пианино",
|
|
87
|
+
duration=8,
|
|
88
|
+
aspect_ratio="16:9",
|
|
89
|
+
)
|
|
90
|
+
print(f"Created task {task.id}, status={task.status}")
|
|
91
|
+
|
|
92
|
+
# Polling до завершения (до 10 минут)
|
|
93
|
+
result = task.wait(timeout=600)
|
|
94
|
+
print(result.video_url)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Возможности
|
|
98
|
+
|
|
99
|
+
- **Все native-параметры** через `**kwargs` — `webhook_url`, `negative_prompt`,
|
|
100
|
+
`image_url`, `cfg_scale`, `video_urls` для seedance, `source_video_url` для veo-extend,
|
|
101
|
+
и т.д. Передаются прямо в `create()`/`generate()`.
|
|
102
|
+
- **Auto-polling** для image-моделей (sync UX). Для видео — `task.wait()`.
|
|
103
|
+
- **Типизированные ошибки** — `NexusError`, `BillingError`, `RateLimitError`,
|
|
104
|
+
`ValidationError`, `NotFoundError`, `NexusTimeoutError`.
|
|
105
|
+
- **Context manager** — `with NexusClient(api_key=...) as client: ...` закрывает
|
|
106
|
+
HTTP-соединение автоматически.
|
|
107
|
+
|
|
108
|
+
## Примеры
|
|
109
|
+
|
|
110
|
+
### Webhook вместо polling
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
task = client.videos.create(
|
|
114
|
+
model="veo-3-fast",
|
|
115
|
+
prompt="...",
|
|
116
|
+
duration=8,
|
|
117
|
+
webhook_url="https://your-app.com/nexus-callback",
|
|
118
|
+
)
|
|
119
|
+
# Не вызываем .wait() — NexusAPI POST'нет на webhook_url когда видео готово
|
|
120
|
+
return task.id # сохраним в БД, дождёмся колбэка
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### Image-to-video (Kling motion)
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
video = client.videos.create(
|
|
127
|
+
model="kling-v2.6-motion-1080p",
|
|
128
|
+
prompt="Камера медленно отъезжает, раскрывая пейзаж",
|
|
129
|
+
duration=8,
|
|
130
|
+
image_url="https://your-bucket.s3.../start-frame.jpg",
|
|
131
|
+
).wait(timeout=600)
|
|
132
|
+
print(video.video_url)
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Image edit (nano-banana)
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
edited = client.images.generate(
|
|
139
|
+
model="nano-banana-pro",
|
|
140
|
+
prompt="Сделай небо более драматичным",
|
|
141
|
+
image_url="https://your-bucket.s3.../photo.jpg",
|
|
142
|
+
)
|
|
143
|
+
print(edited.image_url)
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### Извлечение результата
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
task = client.videos.create(...).wait()
|
|
150
|
+
print(task.video_url) # для видео-моделей
|
|
151
|
+
print(task.image_url) # для image-моделей (берёт первое из image_urls)
|
|
152
|
+
print(task.image_urls) # для image-моделей с несколькими изображениями
|
|
153
|
+
print(task.result) # сырой dict с провайдер-специфичным контентом
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Обработка ошибок
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
from nexusapi import NexusClient, BillingError, RateLimitError, ValidationError
|
|
160
|
+
|
|
161
|
+
try:
|
|
162
|
+
task = client.videos.create(model="veo-3-fast", prompt="...", duration=8).wait()
|
|
163
|
+
except BillingError:
|
|
164
|
+
print("Недостаточно средств — пополни баланс в боте")
|
|
165
|
+
except RateLimitError:
|
|
166
|
+
print("Превышен rate-limit ключа — подожди минуту")
|
|
167
|
+
except ValidationError as e:
|
|
168
|
+
print(f"Невалидные параметры: {e}")
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### Каталог моделей
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
models = client.models.list()
|
|
175
|
+
for m in models:
|
|
176
|
+
print(f"{m['id']}: {m['priceRub']}₽ за {m['unit']}")
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## Документация
|
|
180
|
+
|
|
181
|
+
- [docs.nexusapi.dev](https://docs.nexusapi.dev) — гайды и каталог моделей
|
|
182
|
+
- [docs.nexusapi.dev/api-reference](https://docs.nexusapi.dev/api-reference) — полный API reference
|
|
183
|
+
- [docs.nexusapi.dev/models](https://docs.nexusapi.dev/models) — параметры каждой модели
|
|
184
|
+
|
|
185
|
+
## Лицензия
|
|
186
|
+
|
|
187
|
+
MIT
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# NexusAPI Python SDK
|
|
2
|
+
|
|
3
|
+
Официальный Python SDK для [NexusAPI](https://nexusapi.dev) — единый API для
|
|
4
|
+
генерации видео и изображений через Veo, Kling, Seedance, Nano-Banana и др.
|
|
5
|
+
|
|
6
|
+
## Установка
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install nexusapi-sdk
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
> Пакет на PyPI называется `nexusapi-sdk` (имя `nexusapi` зарезервировано
|
|
13
|
+
> похожим проектом). Импорт остаётся `from nexusapi import ...`.
|
|
14
|
+
|
|
15
|
+
## Quickstart
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from nexusapi import NexusClient
|
|
19
|
+
|
|
20
|
+
client = NexusClient(api_key="ВАШ_КЛЮЧ") # создать в panel.nexusapi.dev
|
|
21
|
+
|
|
22
|
+
# Изображение (sync — SDK сам опрашивает статус)
|
|
23
|
+
img = client.images.generate(
|
|
24
|
+
model="nano-banana",
|
|
25
|
+
prompt="Минималистичный логотип кофейни",
|
|
26
|
+
aspect_ratio="1:1",
|
|
27
|
+
)
|
|
28
|
+
print(img.image_url)
|
|
29
|
+
# → https://nexusapi-s3.../result.png
|
|
30
|
+
|
|
31
|
+
# Видео (async — получаем Task, ждём отдельно)
|
|
32
|
+
task = client.videos.create(
|
|
33
|
+
model="veo-3-fast",
|
|
34
|
+
prompt="Кот играет на пианино",
|
|
35
|
+
duration=8,
|
|
36
|
+
aspect_ratio="16:9",
|
|
37
|
+
)
|
|
38
|
+
print(f"Created task {task.id}, status={task.status}")
|
|
39
|
+
|
|
40
|
+
# Polling до завершения (до 10 минут)
|
|
41
|
+
result = task.wait(timeout=600)
|
|
42
|
+
print(result.video_url)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Возможности
|
|
46
|
+
|
|
47
|
+
- **Все native-параметры** через `**kwargs` — `webhook_url`, `negative_prompt`,
|
|
48
|
+
`image_url`, `cfg_scale`, `video_urls` для seedance, `source_video_url` для veo-extend,
|
|
49
|
+
и т.д. Передаются прямо в `create()`/`generate()`.
|
|
50
|
+
- **Auto-polling** для image-моделей (sync UX). Для видео — `task.wait()`.
|
|
51
|
+
- **Типизированные ошибки** — `NexusError`, `BillingError`, `RateLimitError`,
|
|
52
|
+
`ValidationError`, `NotFoundError`, `NexusTimeoutError`.
|
|
53
|
+
- **Context manager** — `with NexusClient(api_key=...) as client: ...` закрывает
|
|
54
|
+
HTTP-соединение автоматически.
|
|
55
|
+
|
|
56
|
+
## Примеры
|
|
57
|
+
|
|
58
|
+
### Webhook вместо polling
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
task = client.videos.create(
|
|
62
|
+
model="veo-3-fast",
|
|
63
|
+
prompt="...",
|
|
64
|
+
duration=8,
|
|
65
|
+
webhook_url="https://your-app.com/nexus-callback",
|
|
66
|
+
)
|
|
67
|
+
# Не вызываем .wait() — NexusAPI POST'нет на webhook_url когда видео готово
|
|
68
|
+
return task.id # сохраним в БД, дождёмся колбэка
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Image-to-video (Kling motion)
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
video = client.videos.create(
|
|
75
|
+
model="kling-v2.6-motion-1080p",
|
|
76
|
+
prompt="Камера медленно отъезжает, раскрывая пейзаж",
|
|
77
|
+
duration=8,
|
|
78
|
+
image_url="https://your-bucket.s3.../start-frame.jpg",
|
|
79
|
+
).wait(timeout=600)
|
|
80
|
+
print(video.video_url)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Image edit (nano-banana)
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
edited = client.images.generate(
|
|
87
|
+
model="nano-banana-pro",
|
|
88
|
+
prompt="Сделай небо более драматичным",
|
|
89
|
+
image_url="https://your-bucket.s3.../photo.jpg",
|
|
90
|
+
)
|
|
91
|
+
print(edited.image_url)
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Извлечение результата
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
task = client.videos.create(...).wait()
|
|
98
|
+
print(task.video_url) # для видео-моделей
|
|
99
|
+
print(task.image_url) # для image-моделей (берёт первое из image_urls)
|
|
100
|
+
print(task.image_urls) # для image-моделей с несколькими изображениями
|
|
101
|
+
print(task.result) # сырой dict с провайдер-специфичным контентом
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Обработка ошибок
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from nexusapi import NexusClient, BillingError, RateLimitError, ValidationError
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
task = client.videos.create(model="veo-3-fast", prompt="...", duration=8).wait()
|
|
111
|
+
except BillingError:
|
|
112
|
+
print("Недостаточно средств — пополни баланс в боте")
|
|
113
|
+
except RateLimitError:
|
|
114
|
+
print("Превышен rate-limit ключа — подожди минуту")
|
|
115
|
+
except ValidationError as e:
|
|
116
|
+
print(f"Невалидные параметры: {e}")
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### Каталог моделей
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
models = client.models.list()
|
|
123
|
+
for m in models:
|
|
124
|
+
print(f"{m['id']}: {m['priceRub']}₽ за {m['unit']}")
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Документация
|
|
128
|
+
|
|
129
|
+
- [docs.nexusapi.dev](https://docs.nexusapi.dev) — гайды и каталог моделей
|
|
130
|
+
- [docs.nexusapi.dev/api-reference](https://docs.nexusapi.dev/api-reference) — полный API reference
|
|
131
|
+
- [docs.nexusapi.dev/models](https://docs.nexusapi.dev/models) — параметры каждой модели
|
|
132
|
+
|
|
133
|
+
## Лицензия
|
|
134
|
+
|
|
135
|
+
MIT
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""NexusAPI Python SDK.
|
|
2
|
+
|
|
3
|
+
Quickstart:
|
|
4
|
+
|
|
5
|
+
from nexusapi import NexusClient
|
|
6
|
+
|
|
7
|
+
client = NexusClient(api_key="...")
|
|
8
|
+
|
|
9
|
+
# Image (sync — built-in polling)
|
|
10
|
+
img = client.images.generate(model="nano-banana", prompt="a cat")
|
|
11
|
+
print(img.image_url)
|
|
12
|
+
|
|
13
|
+
# Video (async — get a Task, wait if needed)
|
|
14
|
+
task = client.videos.create(model="veo-3-fast", prompt="a cat", duration=8)
|
|
15
|
+
result = task.wait(timeout=600)
|
|
16
|
+
print(result.video_url)
|
|
17
|
+
"""
|
|
18
|
+
from .client import NexusClient, Task
|
|
19
|
+
from .errors import (
|
|
20
|
+
NexusError,
|
|
21
|
+
AuthenticationError,
|
|
22
|
+
BillingError,
|
|
23
|
+
PermissionError as NexusPermissionError,
|
|
24
|
+
RateLimitError,
|
|
25
|
+
ValidationError,
|
|
26
|
+
NotFoundError,
|
|
27
|
+
TimeoutError as NexusTimeoutError,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__version__ = "0.1.0"
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"NexusClient",
|
|
34
|
+
"Task",
|
|
35
|
+
"NexusError",
|
|
36
|
+
"AuthenticationError",
|
|
37
|
+
"BillingError",
|
|
38
|
+
"NexusPermissionError",
|
|
39
|
+
"RateLimitError",
|
|
40
|
+
"ValidationError",
|
|
41
|
+
"NotFoundError",
|
|
42
|
+
"NexusTimeoutError",
|
|
43
|
+
]
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""Основной клиент SDK и Task-объект.
|
|
2
|
+
|
|
3
|
+
Дизайн вдохновлён OpenAI/Stripe-стилем: client.<resource>.<verb>(...). Без
|
|
4
|
+
магии и метапрограммирования — обычные методы, типы видны.
|
|
5
|
+
"""
|
|
6
|
+
import time
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any, Optional
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from . import errors
|
|
13
|
+
|
|
14
|
+
DEFAULT_BASE_URL = "https://nexusapi.dev"
|
|
15
|
+
DEFAULT_TIMEOUT = 60.0
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _raise_for_status(resp: httpx.Response) -> None:
|
|
19
|
+
"""Маппит HTTP-код в типизированное исключение SDK."""
|
|
20
|
+
body = None
|
|
21
|
+
message = f"HTTP {resp.status_code}"
|
|
22
|
+
try:
|
|
23
|
+
body = resp.json()
|
|
24
|
+
if isinstance(body.get("error"), dict) and body["error"].get("message"):
|
|
25
|
+
# OpenAI-shape (/v1/*)
|
|
26
|
+
message = body["error"]["message"]
|
|
27
|
+
elif isinstance(body.get("detail"), str):
|
|
28
|
+
# FastAPI string detail
|
|
29
|
+
message = body["detail"]
|
|
30
|
+
elif isinstance(body.get("detail"), list) and body["detail"]:
|
|
31
|
+
# Pydantic-validation массив с loc/msg
|
|
32
|
+
first = body["detail"][0]
|
|
33
|
+
loc = ".".join(str(x) for x in (first.get("loc") or [])[1:]) or "request"
|
|
34
|
+
msg = first.get("msg") or "invalid"
|
|
35
|
+
message = f"{loc}: {msg}"
|
|
36
|
+
elif resp.text:
|
|
37
|
+
message = resp.text
|
|
38
|
+
except Exception:
|
|
39
|
+
if resp.text:
|
|
40
|
+
message = resp.text
|
|
41
|
+
|
|
42
|
+
code = resp.status_code
|
|
43
|
+
cls = {
|
|
44
|
+
400: errors.ValidationError,
|
|
45
|
+
401: errors.AuthenticationError,
|
|
46
|
+
402: errors.BillingError,
|
|
47
|
+
403: errors.PermissionError,
|
|
48
|
+
404: errors.NotFoundError,
|
|
49
|
+
422: errors.ValidationError,
|
|
50
|
+
429: errors.RateLimitError,
|
|
51
|
+
}.get(code, errors.NexusError)
|
|
52
|
+
raise cls(message, status_code=code, response_body=body)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# ============================================================
|
|
56
|
+
# Task
|
|
57
|
+
# ============================================================
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class Task:
|
|
61
|
+
"""Задача генерации. Возвращается всеми create/generate-методами."""
|
|
62
|
+
id: str
|
|
63
|
+
status: str
|
|
64
|
+
model: Optional[str] = None
|
|
65
|
+
result: Optional[dict] = None
|
|
66
|
+
error: Optional[str] = None
|
|
67
|
+
created_at: Optional[str] = None
|
|
68
|
+
# Приватная ссылка на клиент для refresh()/wait()
|
|
69
|
+
_client: Optional["NexusClient"] = field(default=None, repr=False, compare=False)
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def is_done(self) -> bool:
|
|
73
|
+
return self.status in ("completed", "failed")
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def video_url(self) -> Optional[str]:
|
|
77
|
+
return (self.result or {}).get("video_url")
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def image_url(self) -> Optional[str]:
|
|
81
|
+
"""Берёт image_urls[0] (для моделей возвращающих список) или image_url."""
|
|
82
|
+
r = self.result or {}
|
|
83
|
+
urls = r.get("image_urls")
|
|
84
|
+
if isinstance(urls, list) and urls:
|
|
85
|
+
return urls[0]
|
|
86
|
+
return r.get("image_url")
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def image_urls(self) -> list:
|
|
90
|
+
return list((self.result or {}).get("image_urls") or [])
|
|
91
|
+
|
|
92
|
+
def refresh(self) -> "Task":
|
|
93
|
+
"""Перезапрашивает статус. Возвращает self для chain'инга."""
|
|
94
|
+
if self._client is None:
|
|
95
|
+
raise errors.NexusError("Task not bound to a client — cannot refresh")
|
|
96
|
+
fresh = self._client.tasks.get(self.id)
|
|
97
|
+
self.status = fresh.status
|
|
98
|
+
self.result = fresh.result
|
|
99
|
+
self.error = fresh.error
|
|
100
|
+
self.created_at = fresh.created_at or self.created_at
|
|
101
|
+
self.model = fresh.model or self.model
|
|
102
|
+
return self
|
|
103
|
+
|
|
104
|
+
def wait(self, timeout: float = 600, poll_interval: float = 3.0) -> "Task":
|
|
105
|
+
"""Блокируется до завершения задачи. Бросает NexusTimeoutError по таймауту,
|
|
106
|
+
NexusError если задача упала."""
|
|
107
|
+
deadline = time.monotonic() + timeout
|
|
108
|
+
while not self.is_done:
|
|
109
|
+
if time.monotonic() > deadline:
|
|
110
|
+
raise errors.TimeoutError(
|
|
111
|
+
f"Task {self.id} did not complete within {timeout}s"
|
|
112
|
+
)
|
|
113
|
+
time.sleep(poll_interval)
|
|
114
|
+
self.refresh()
|
|
115
|
+
if self.status == "failed":
|
|
116
|
+
raise errors.NexusError(
|
|
117
|
+
f"Task {self.id} failed: {self.error or 'unknown error'}",
|
|
118
|
+
response_body={"task_id": self.id, "error": self.error},
|
|
119
|
+
)
|
|
120
|
+
return self
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# ============================================================
|
|
124
|
+
# Resources
|
|
125
|
+
# ============================================================
|
|
126
|
+
|
|
127
|
+
class _Resource:
|
|
128
|
+
def __init__(self, client: "NexusClient"):
|
|
129
|
+
self._client = client
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class Videos(_Resource):
|
|
133
|
+
"""Видео — async-only. create() → Task → task.wait() либо task.refresh()."""
|
|
134
|
+
|
|
135
|
+
def create(
|
|
136
|
+
self,
|
|
137
|
+
*,
|
|
138
|
+
model: str,
|
|
139
|
+
prompt: str,
|
|
140
|
+
duration: Optional[int] = None,
|
|
141
|
+
aspect_ratio: Optional[str] = None,
|
|
142
|
+
idempotency_key: Optional[str] = None,
|
|
143
|
+
**extras: Any,
|
|
144
|
+
) -> Task:
|
|
145
|
+
"""Создаёт видео-задачу. Возвращает Task в статусе pending.
|
|
146
|
+
|
|
147
|
+
Args:
|
|
148
|
+
idempotency_key: Опционально. При повторе с тем же ключом
|
|
149
|
+
возвращает тот же task_id без второго списания.
|
|
150
|
+
См. docs.nexusapi.dev/concepts/idempotency.
|
|
151
|
+
"""
|
|
152
|
+
params: dict[str, Any] = {"model_name": model, "prompt": prompt}
|
|
153
|
+
if duration is not None:
|
|
154
|
+
params["duration"] = duration
|
|
155
|
+
if aspect_ratio is not None:
|
|
156
|
+
params["aspect_ratio"] = aspect_ratio
|
|
157
|
+
params.update({k: v for k, v in extras.items() if v is not None})
|
|
158
|
+
headers = {"Idempotency-Key": idempotency_key} if idempotency_key else None
|
|
159
|
+
data = self._client._request(
|
|
160
|
+
"POST", "/generate", json={"params": params}, extra_headers=headers,
|
|
161
|
+
)
|
|
162
|
+
return Task(
|
|
163
|
+
id=data["task_id"],
|
|
164
|
+
status="pending",
|
|
165
|
+
model=model,
|
|
166
|
+
_client=self._client,
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class Images(_Resource):
|
|
171
|
+
"""Изображения. По умолчанию generate() ждёт завершения (синхронный UX);
|
|
172
|
+
можно отключить через wait=False, тогда вернётся Task в pending."""
|
|
173
|
+
|
|
174
|
+
def generate(
|
|
175
|
+
self,
|
|
176
|
+
*,
|
|
177
|
+
model: str,
|
|
178
|
+
prompt: str,
|
|
179
|
+
aspect_ratio: Optional[str] = None,
|
|
180
|
+
wait: bool = True,
|
|
181
|
+
timeout: float = 180,
|
|
182
|
+
poll_interval: float = 1.5,
|
|
183
|
+
idempotency_key: Optional[str] = None,
|
|
184
|
+
**extras: Any,
|
|
185
|
+
) -> Task:
|
|
186
|
+
"""Создаёт image-задачу и (по умолчанию) ждёт завершения.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
idempotency_key: Опционально. При повторе с тем же ключом
|
|
190
|
+
возвращает тот же task без второй генерации/списания.
|
|
191
|
+
"""
|
|
192
|
+
params: dict[str, Any] = {"model_name": model, "prompt": prompt}
|
|
193
|
+
if aspect_ratio is not None:
|
|
194
|
+
params["aspect_ratio"] = aspect_ratio
|
|
195
|
+
params.update({k: v for k, v in extras.items() if v is not None})
|
|
196
|
+
headers = {"Idempotency-Key": idempotency_key} if idempotency_key else None
|
|
197
|
+
data = self._client._request(
|
|
198
|
+
"POST", "/generate", json={"params": params}, extra_headers=headers,
|
|
199
|
+
)
|
|
200
|
+
task = Task(
|
|
201
|
+
id=data["task_id"], status="pending", model=model, _client=self._client,
|
|
202
|
+
)
|
|
203
|
+
if wait:
|
|
204
|
+
task.wait(timeout=timeout, poll_interval=poll_interval)
|
|
205
|
+
return task
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class Tasks(_Resource):
|
|
209
|
+
def get(self, task_id: str) -> Task:
|
|
210
|
+
data = self._client._request("GET", f"/tasks/{task_id}")
|
|
211
|
+
return Task(
|
|
212
|
+
id=data["task_id"],
|
|
213
|
+
status=data["status"],
|
|
214
|
+
model=None,
|
|
215
|
+
result=data.get("result"),
|
|
216
|
+
error=data.get("error"),
|
|
217
|
+
created_at=data.get("created_at"),
|
|
218
|
+
_client=self._client,
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class Models(_Resource):
|
|
223
|
+
def list(self) -> list[dict]:
|
|
224
|
+
"""Возвращает каталог моделей. Без auth (используется публичный эндпоинт)."""
|
|
225
|
+
return self._client._request("GET", "/public/models", auth=False)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
# ============================================================
|
|
229
|
+
# Client
|
|
230
|
+
# ============================================================
|
|
231
|
+
|
|
232
|
+
class NexusClient:
|
|
233
|
+
"""Главный клиент NexusAPI.
|
|
234
|
+
|
|
235
|
+
Args:
|
|
236
|
+
api_key: Bearer-токен. Создаётся в panel.nexusapi.dev → API ключи.
|
|
237
|
+
base_url: URL API. Дефолт https://nexusapi.dev.
|
|
238
|
+
timeout: Таймаут HTTP-запросов в секундах. Дефолт 60.
|
|
239
|
+
"""
|
|
240
|
+
|
|
241
|
+
def __init__(
|
|
242
|
+
self,
|
|
243
|
+
api_key: str,
|
|
244
|
+
*,
|
|
245
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
246
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
247
|
+
):
|
|
248
|
+
if not api_key:
|
|
249
|
+
raise errors.AuthenticationError("api_key is required")
|
|
250
|
+
self._api_key = api_key
|
|
251
|
+
self._base_url = base_url.rstrip("/")
|
|
252
|
+
self._http = httpx.Client(
|
|
253
|
+
timeout=timeout,
|
|
254
|
+
headers={"User-Agent": f"nexusapi-python/{_get_version()}"},
|
|
255
|
+
)
|
|
256
|
+
self.videos = Videos(self)
|
|
257
|
+
self.images = Images(self)
|
|
258
|
+
self.tasks = Tasks(self)
|
|
259
|
+
self.models = Models(self)
|
|
260
|
+
|
|
261
|
+
def _request(
|
|
262
|
+
self,
|
|
263
|
+
method: str,
|
|
264
|
+
path: str,
|
|
265
|
+
*,
|
|
266
|
+
json: Optional[dict] = None,
|
|
267
|
+
params: Optional[dict] = None,
|
|
268
|
+
auth: bool = True,
|
|
269
|
+
extra_headers: Optional[dict] = None,
|
|
270
|
+
) -> Any:
|
|
271
|
+
url = f"{self._base_url}{path}"
|
|
272
|
+
headers = {}
|
|
273
|
+
if auth:
|
|
274
|
+
headers["Authorization"] = f"Bearer {self._api_key}"
|
|
275
|
+
if extra_headers:
|
|
276
|
+
headers.update(extra_headers)
|
|
277
|
+
resp = self._http.request(
|
|
278
|
+
method, url, json=json, params=params, headers=headers,
|
|
279
|
+
)
|
|
280
|
+
if not resp.is_success:
|
|
281
|
+
_raise_for_status(resp)
|
|
282
|
+
if resp.status_code == 204 or not resp.content:
|
|
283
|
+
return None
|
|
284
|
+
return resp.json()
|
|
285
|
+
|
|
286
|
+
def close(self) -> None:
|
|
287
|
+
self._http.close()
|
|
288
|
+
|
|
289
|
+
def __enter__(self):
|
|
290
|
+
return self
|
|
291
|
+
|
|
292
|
+
def __exit__(self, *args):
|
|
293
|
+
self.close()
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _get_version() -> str:
|
|
297
|
+
"""Версия пакета — используется в User-Agent."""
|
|
298
|
+
try:
|
|
299
|
+
from . import __version__
|
|
300
|
+
return __version__
|
|
301
|
+
except Exception:
|
|
302
|
+
return "0.0.0"
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Иерархия исключений SDK.
|
|
2
|
+
|
|
3
|
+
Все исключения наследуются от NexusError — `except NexusError` ловит всё.
|
|
4
|
+
"""
|
|
5
|
+
from typing import Any, Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class NexusError(Exception):
|
|
9
|
+
"""Базовое исключение. Несёт HTTP-статус и raw-ответ для отладки."""
|
|
10
|
+
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
message: str,
|
|
14
|
+
status_code: Optional[int] = None,
|
|
15
|
+
response_body: Optional[Any] = None,
|
|
16
|
+
):
|
|
17
|
+
super().__init__(message)
|
|
18
|
+
self.status_code = status_code
|
|
19
|
+
self.response_body = response_body
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AuthenticationError(NexusError):
|
|
23
|
+
"""401 — нет ключа, ключ невалидный или отозван."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PermissionError(NexusError):
|
|
27
|
+
"""403 — restrictions ключа (IP / allowed_models)."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class BillingError(NexusError):
|
|
31
|
+
"""402 — баланса не хватает."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class RateLimitError(NexusError):
|
|
35
|
+
"""429 — превышен rate_limit_per_min ключа."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ValidationError(NexusError):
|
|
39
|
+
"""400/422 — невалидные параметры запроса."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class NotFoundError(NexusError):
|
|
43
|
+
"""404 — задача / ключ / модель не найдены."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class TimeoutError(NexusError): # noqa: A001 — намеренно перекрываем builtin
|
|
47
|
+
"""Task.wait() превысил deadline без завершения задачи."""
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: nexusapi-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK для NexusAPI — генерация видео и изображений через единый API (Veo, Kling, Seedance, Nano-Banana)
|
|
5
|
+
Author-email: NexusAPI <support@nexusapi.dev>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2026 NexusAPI
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://nexusapi.dev
|
|
29
|
+
Project-URL: Documentation, https://docs.nexusapi.dev
|
|
30
|
+
Project-URL: Repository, https://github.com/EmilJaf/main-api-v1
|
|
31
|
+
Project-URL: Issues, https://github.com/EmilJaf/main-api-v1/issues
|
|
32
|
+
Keywords: ai,video,image,generation,veo,kling,seedance,nano-banana,sora,openai-compatible,idempotency-key
|
|
33
|
+
Classifier: Development Status :: 4 - Beta
|
|
34
|
+
Classifier: Intended Audience :: Developers
|
|
35
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
36
|
+
Classifier: Operating System :: OS Independent
|
|
37
|
+
Classifier: Programming Language :: Python :: 3
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
42
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
43
|
+
Classifier: Topic :: Multimedia :: Graphics
|
|
44
|
+
Classifier: Topic :: Multimedia :: Video
|
|
45
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
46
|
+
Classifier: Typing :: Typed
|
|
47
|
+
Requires-Python: >=3.9
|
|
48
|
+
Description-Content-Type: text/markdown
|
|
49
|
+
License-File: LICENSE
|
|
50
|
+
Requires-Dist: httpx>=0.24
|
|
51
|
+
Dynamic: license-file
|
|
52
|
+
|
|
53
|
+
# NexusAPI Python SDK
|
|
54
|
+
|
|
55
|
+
Официальный Python SDK для [NexusAPI](https://nexusapi.dev) — единый API для
|
|
56
|
+
генерации видео и изображений через Veo, Kling, Seedance, Nano-Banana и др.
|
|
57
|
+
|
|
58
|
+
## Установка
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pip install nexusapi-sdk
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
> Пакет на PyPI называется `nexusapi-sdk` (имя `nexusapi` зарезервировано
|
|
65
|
+
> похожим проектом). Импорт остаётся `from nexusapi import ...`.
|
|
66
|
+
|
|
67
|
+
## Quickstart
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from nexusapi import NexusClient
|
|
71
|
+
|
|
72
|
+
client = NexusClient(api_key="ВАШ_КЛЮЧ") # создать в panel.nexusapi.dev
|
|
73
|
+
|
|
74
|
+
# Изображение (sync — SDK сам опрашивает статус)
|
|
75
|
+
img = client.images.generate(
|
|
76
|
+
model="nano-banana",
|
|
77
|
+
prompt="Минималистичный логотип кофейни",
|
|
78
|
+
aspect_ratio="1:1",
|
|
79
|
+
)
|
|
80
|
+
print(img.image_url)
|
|
81
|
+
# → https://nexusapi-s3.../result.png
|
|
82
|
+
|
|
83
|
+
# Видео (async — получаем Task, ждём отдельно)
|
|
84
|
+
task = client.videos.create(
|
|
85
|
+
model="veo-3-fast",
|
|
86
|
+
prompt="Кот играет на пианино",
|
|
87
|
+
duration=8,
|
|
88
|
+
aspect_ratio="16:9",
|
|
89
|
+
)
|
|
90
|
+
print(f"Created task {task.id}, status={task.status}")
|
|
91
|
+
|
|
92
|
+
# Polling до завершения (до 10 минут)
|
|
93
|
+
result = task.wait(timeout=600)
|
|
94
|
+
print(result.video_url)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Возможности
|
|
98
|
+
|
|
99
|
+
- **Все native-параметры** через `**kwargs` — `webhook_url`, `negative_prompt`,
|
|
100
|
+
`image_url`, `cfg_scale`, `video_urls` для seedance, `source_video_url` для veo-extend,
|
|
101
|
+
и т.д. Передаются прямо в `create()`/`generate()`.
|
|
102
|
+
- **Auto-polling** для image-моделей (sync UX). Для видео — `task.wait()`.
|
|
103
|
+
- **Типизированные ошибки** — `NexusError`, `BillingError`, `RateLimitError`,
|
|
104
|
+
`ValidationError`, `NotFoundError`, `NexusTimeoutError`.
|
|
105
|
+
- **Context manager** — `with NexusClient(api_key=...) as client: ...` закрывает
|
|
106
|
+
HTTP-соединение автоматически.
|
|
107
|
+
|
|
108
|
+
## Примеры
|
|
109
|
+
|
|
110
|
+
### Webhook вместо polling
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
task = client.videos.create(
|
|
114
|
+
model="veo-3-fast",
|
|
115
|
+
prompt="...",
|
|
116
|
+
duration=8,
|
|
117
|
+
webhook_url="https://your-app.com/nexus-callback",
|
|
118
|
+
)
|
|
119
|
+
# Не вызываем .wait() — NexusAPI POST'нет на webhook_url когда видео готово
|
|
120
|
+
return task.id # сохраним в БД, дождёмся колбэка
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### Image-to-video (Kling motion)
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
video = client.videos.create(
|
|
127
|
+
model="kling-v2.6-motion-1080p",
|
|
128
|
+
prompt="Камера медленно отъезжает, раскрывая пейзаж",
|
|
129
|
+
duration=8,
|
|
130
|
+
image_url="https://your-bucket.s3.../start-frame.jpg",
|
|
131
|
+
).wait(timeout=600)
|
|
132
|
+
print(video.video_url)
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Image edit (nano-banana)
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
edited = client.images.generate(
|
|
139
|
+
model="nano-banana-pro",
|
|
140
|
+
prompt="Сделай небо более драматичным",
|
|
141
|
+
image_url="https://your-bucket.s3.../photo.jpg",
|
|
142
|
+
)
|
|
143
|
+
print(edited.image_url)
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### Извлечение результата
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
task = client.videos.create(...).wait()
|
|
150
|
+
print(task.video_url) # для видео-моделей
|
|
151
|
+
print(task.image_url) # для image-моделей (берёт первое из image_urls)
|
|
152
|
+
print(task.image_urls) # для image-моделей с несколькими изображениями
|
|
153
|
+
print(task.result) # сырой dict с провайдер-специфичным контентом
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Обработка ошибок
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
from nexusapi import NexusClient, BillingError, RateLimitError, ValidationError
|
|
160
|
+
|
|
161
|
+
try:
|
|
162
|
+
task = client.videos.create(model="veo-3-fast", prompt="...", duration=8).wait()
|
|
163
|
+
except BillingError:
|
|
164
|
+
print("Недостаточно средств — пополни баланс в боте")
|
|
165
|
+
except RateLimitError:
|
|
166
|
+
print("Превышен rate-limit ключа — подожди минуту")
|
|
167
|
+
except ValidationError as e:
|
|
168
|
+
print(f"Невалидные параметры: {e}")
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### Каталог моделей
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
models = client.models.list()
|
|
175
|
+
for m in models:
|
|
176
|
+
print(f"{m['id']}: {m['priceRub']}₽ за {m['unit']}")
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## Документация
|
|
180
|
+
|
|
181
|
+
- [docs.nexusapi.dev](https://docs.nexusapi.dev) — гайды и каталог моделей
|
|
182
|
+
- [docs.nexusapi.dev/api-reference](https://docs.nexusapi.dev/api-reference) — полный API reference
|
|
183
|
+
- [docs.nexusapi.dev/models](https://docs.nexusapi.dev/models) — параметры каждой модели
|
|
184
|
+
|
|
185
|
+
## Лицензия
|
|
186
|
+
|
|
187
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
nexusapi/__init__.py
|
|
5
|
+
nexusapi/client.py
|
|
6
|
+
nexusapi/errors.py
|
|
7
|
+
nexusapi_sdk.egg-info/PKG-INFO
|
|
8
|
+
nexusapi_sdk.egg-info/SOURCES.txt
|
|
9
|
+
nexusapi_sdk.egg-info/dependency_links.txt
|
|
10
|
+
nexusapi_sdk.egg-info/requires.txt
|
|
11
|
+
nexusapi_sdk.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
httpx>=0.24
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
nexusapi
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=64"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "nexusapi-sdk"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python SDK для NexusAPI — генерация видео и изображений через единый API (Veo, Kling, Seedance, Nano-Banana)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { file = "LICENSE" }
|
|
12
|
+
authors = [{ name = "NexusAPI", email = "support@nexusapi.dev" }]
|
|
13
|
+
keywords = [
|
|
14
|
+
"ai", "video", "image", "generation",
|
|
15
|
+
"veo", "kling", "seedance", "nano-banana",
|
|
16
|
+
"sora", "openai-compatible", "idempotency-key",
|
|
17
|
+
]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 4 - Beta",
|
|
20
|
+
"Intended Audience :: Developers",
|
|
21
|
+
"License :: OSI Approved :: MIT License",
|
|
22
|
+
"Operating System :: OS Independent",
|
|
23
|
+
"Programming Language :: Python :: 3",
|
|
24
|
+
"Programming Language :: Python :: 3.9",
|
|
25
|
+
"Programming Language :: Python :: 3.10",
|
|
26
|
+
"Programming Language :: Python :: 3.11",
|
|
27
|
+
"Programming Language :: Python :: 3.12",
|
|
28
|
+
"Programming Language :: Python :: 3.13",
|
|
29
|
+
"Topic :: Multimedia :: Graphics",
|
|
30
|
+
"Topic :: Multimedia :: Video",
|
|
31
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
32
|
+
"Typing :: Typed",
|
|
33
|
+
]
|
|
34
|
+
dependencies = [
|
|
35
|
+
"httpx >= 0.24",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[project.urls]
|
|
39
|
+
Homepage = "https://nexusapi.dev"
|
|
40
|
+
Documentation = "https://docs.nexusapi.dev"
|
|
41
|
+
Repository = "https://github.com/EmilJaf/main-api-v1"
|
|
42
|
+
Issues = "https://github.com/EmilJaf/main-api-v1/issues"
|
|
43
|
+
|
|
44
|
+
[tool.setuptools.packages.find]
|
|
45
|
+
include = ["nexusapi*"]
|