dcmarket 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.
- dcmarket-0.1.0/.gitignore +8 -0
- dcmarket-0.1.0/PKG-INFO +127 -0
- dcmarket-0.1.0/README.md +109 -0
- dcmarket-0.1.0/pyproject.toml +34 -0
- dcmarket-0.1.0/src/dcmarket/__init__.py +13 -0
- dcmarket-0.1.0/src/dcmarket/client.py +153 -0
- dcmarket-0.1.0/src/dcmarket/errors.py +47 -0
- dcmarket-0.1.0/src/dcmarket/images.py +161 -0
- dcmarket-0.1.0/src/dcmarket/py.typed +0 -0
- dcmarket-0.1.0/src/dcmarket/types.py +19 -0
- dcmarket-0.1.0/src/dcmarket/videos.py +321 -0
- dcmarket-0.1.0/tests/test_client.py +104 -0
- dcmarket-0.1.0/tests/test_images.py +253 -0
- dcmarket-0.1.0/tests/test_videos.py +313 -0
dcmarket-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: dcmarket
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Sync and asyncio Python clients for the DC Market video and image APIs
|
|
5
|
+
Project-URL: Homepage, https://market.dcaidc.com
|
|
6
|
+
Author: dongchuang
|
|
7
|
+
Classifier: Framework :: AsyncIO
|
|
8
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
9
|
+
Classifier: Topic :: Multimedia :: Graphics
|
|
10
|
+
Classifier: Topic :: Multimedia :: Video
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Requires-Dist: httpx<1,>=0.27
|
|
14
|
+
Provides-Extra: test
|
|
15
|
+
Requires-Dist: pytest-cov>=5; extra == 'test'
|
|
16
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# dcmarket
|
|
20
|
+
|
|
21
|
+
DC Market 图片和视频接口的 Python SDK,支持 Python 3.10 及以上版本。普通脚本使用 `DCMarket`,asyncio 服务使用 `AsyncDCMarket`。两者的方法名、参数和结果字段一致。
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
python -m pip install dcmarket
|
|
25
|
+
export DCMARKET_API_KEY='你的平台 API Key'
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
默认 API 地址为 `https://market.dcaidc.com/v1`。也可在创建客户端时显式传入 `api_key`、`base_url`、`timeout`(单次 HTTP 操作超时秒数)。示例中的模型名请按账号已开通的模型替换。
|
|
29
|
+
|
|
30
|
+
## 同步生成和编辑图片
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from dcmarket import DCMarket
|
|
34
|
+
|
|
35
|
+
with DCMarket() as dc:
|
|
36
|
+
result = dc.images.generate(
|
|
37
|
+
model="gpt-image-2",
|
|
38
|
+
prompt="靠窗的木桌上放着一只白瓷咖啡杯,商品摄影",
|
|
39
|
+
)
|
|
40
|
+
print(result.data[0].url)
|
|
41
|
+
|
|
42
|
+
edited = dc.images.edit(
|
|
43
|
+
model="gpt-image-2",
|
|
44
|
+
image=result.data[0].url,
|
|
45
|
+
prompt="把杯身改成深蓝色,保留把手和窗边的光线",
|
|
46
|
+
)
|
|
47
|
+
print(edited.data[0].url)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
编辑本地图片时,传入 `pathlib.Path("cup.png")`;多图可传 `[Path("front.png"), Path("side.png")]`。蒙版用 `mask=Path("mask.png")`。同一次编辑请统一使用本地文件或字符串素材。请求 `response_format="b64_json"` 时,从 `result.data[0].b64_json` 读取结果。完整服务端响应保存在 `result.raw`。
|
|
51
|
+
|
|
52
|
+
## 异步生成视频
|
|
53
|
+
|
|
54
|
+
下面的程序接收一张参考图和一段音频的公网 URL。视频任务提交后会先打印 ID,等生成完成再打印下载地址。
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
import asyncio
|
|
58
|
+
import sys
|
|
59
|
+
|
|
60
|
+
from dcmarket import AspectRatio, AsyncDCMarket, Resolution
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
async def main(image_url: str, audio_url: str) -> None:
|
|
64
|
+
async with AsyncDCMarket() as dc:
|
|
65
|
+
task = await dc.videos.generate(
|
|
66
|
+
model="doubao-seedance-2-0-260128-max",
|
|
67
|
+
prompt="保持杯身图案,镜头随参考音频的鼓点推进。",
|
|
68
|
+
reference_images=[image_url],
|
|
69
|
+
reference_audios=[audio_url],
|
|
70
|
+
resolution=Resolution.P720,
|
|
71
|
+
aspect_ratio=AspectRatio.R9_16,
|
|
72
|
+
duration=5,
|
|
73
|
+
generate_audio=True,
|
|
74
|
+
)
|
|
75
|
+
print(task.id, flush=True)
|
|
76
|
+
video = await task.wait(timeout=600)
|
|
77
|
+
print(video.url)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
if __name__ == "__main__":
|
|
81
|
+
asyncio.run(main(sys.argv[1], sys.argv[2]))
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
在同一事件循环中可复用一个异步客户端,例如用 `await asyncio.gather(task_a.wait(), task_b.wait())` 等待多个任务。同步视频接口的调用如下。
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
from dcmarket import DCMarket
|
|
88
|
+
|
|
89
|
+
with DCMarket() as dc:
|
|
90
|
+
task = dc.videos.generate(
|
|
91
|
+
model="doubao-seedance-2-0-260128-max",
|
|
92
|
+
prompt="清晨的阳光缓慢照进陶艺工作室",
|
|
93
|
+
duration=5,
|
|
94
|
+
)
|
|
95
|
+
print(task.id, flush=True)
|
|
96
|
+
print(task.wait(timeout=600).url)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## 视频参数
|
|
100
|
+
|
|
101
|
+
| 参数 | 用法 |
|
|
102
|
+
| --- | --- |
|
|
103
|
+
| `model`、`prompt` | 传平台模型名与提示词;支持素材或草稿输入的模型可省略提示词 |
|
|
104
|
+
| `duration` | 视频时长,单位为秒 |
|
|
105
|
+
| `resolution` | `Resolution.P480`、`P720`、`P1080`,或模型支持的字符串,如 `"720p"` |
|
|
106
|
+
| `aspect_ratio` | `AspectRatio.R16_9`、`R9_16`、`R1_1`、`R4_3`、`R3_4`、`R21_9`、`ADAPTIVE`,或字符串,如 `"9:16"` |
|
|
107
|
+
| `size` | 平台尺寸字段,如 `"1280x720"`;具体档位由模型决定 |
|
|
108
|
+
| `first_frame_image`、`last_frame_image` | 首帧和尾帧,各传一张图的 URL 或模型支持的 data URI |
|
|
109
|
+
| `reference_images`、`reference_videos`、`reference_audios` | 分别传有序的素材 URL 列表。模型按列表顺序引用素材 |
|
|
110
|
+
| `generate_audio`、`seed`、`watermark` | 生成带音频的成片、随机种子和水印开关;按模型能力使用 |
|
|
111
|
+
| `metadata`、`draft_task`、`extra_body` | 模型扩展。使用 `extra_body={"content": [...]}` 可发送原生字段 |
|
|
112
|
+
|
|
113
|
+
## 编辑、延长和恢复视频任务
|
|
114
|
+
|
|
115
|
+
| 同步调用 | 返回结果 |
|
|
116
|
+
| --- | --- |
|
|
117
|
+
| `dc.videos.edit(model=..., video=source_url, prompt=...)` | 视频编辑任务,可指定 `reference_images` |
|
|
118
|
+
| `dc.videos.extend(model=..., video=source_url, prompt=..., duration=5)` | 视频延长任务,`duration` 为新增秒数 |
|
|
119
|
+
| `dc.videos.get(task_id)` | 当前任务,包含 `.id`、`.status`、`.url` 和 `.raw` |
|
|
120
|
+
| `task.wait(timeout=600, poll_interval=5)` | 已完成的视频任务;在创建此任务的客户端关闭前调用 |
|
|
121
|
+
| `dc.videos.content_url(task_id)` | 获取可用于下载成片的链接 |
|
|
122
|
+
|
|
123
|
+
异步客户端对以上调用使用 `await`。等待超时会抛出 `TaskTimeoutError`。保留原任务 ID,稍后用 `dc.videos.get(task_id)` 取回任务并继续 `.wait()`。取消异步等待时,远端已提交的任务会继续处理。
|
|
124
|
+
|
|
125
|
+
异步 `wait(timeout=...)` 会在等待期限到达时取消当前查询。同步客户端在两次查询之间检查期限,也会把剩余时间用于当前请求的网络超时。如果服务器持续缓慢地发送数据,同步调用可能要等当前响应结束才抛出超时异常。
|
|
126
|
+
|
|
127
|
+
任务失败时,`TaskFailedError` 提供 `task_id`、`code` 和 `message`。HTTP 错误通过 `APIError` 提供 `status_code`、`code`、`message` 和可用的 `request_id`。遇到 `NetworkError` 时,创建请求可能已被平台受理,SDK 不会自动重提付费任务。
|
dcmarket-0.1.0/README.md
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# dcmarket
|
|
2
|
+
|
|
3
|
+
DC Market 图片和视频接口的 Python SDK,支持 Python 3.10 及以上版本。普通脚本使用 `DCMarket`,asyncio 服务使用 `AsyncDCMarket`。两者的方法名、参数和结果字段一致。
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
python -m pip install dcmarket
|
|
7
|
+
export DCMARKET_API_KEY='你的平台 API Key'
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
默认 API 地址为 `https://market.dcaidc.com/v1`。也可在创建客户端时显式传入 `api_key`、`base_url`、`timeout`(单次 HTTP 操作超时秒数)。示例中的模型名请按账号已开通的模型替换。
|
|
11
|
+
|
|
12
|
+
## 同步生成和编辑图片
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from dcmarket import DCMarket
|
|
16
|
+
|
|
17
|
+
with DCMarket() as dc:
|
|
18
|
+
result = dc.images.generate(
|
|
19
|
+
model="gpt-image-2",
|
|
20
|
+
prompt="靠窗的木桌上放着一只白瓷咖啡杯,商品摄影",
|
|
21
|
+
)
|
|
22
|
+
print(result.data[0].url)
|
|
23
|
+
|
|
24
|
+
edited = dc.images.edit(
|
|
25
|
+
model="gpt-image-2",
|
|
26
|
+
image=result.data[0].url,
|
|
27
|
+
prompt="把杯身改成深蓝色,保留把手和窗边的光线",
|
|
28
|
+
)
|
|
29
|
+
print(edited.data[0].url)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
编辑本地图片时,传入 `pathlib.Path("cup.png")`;多图可传 `[Path("front.png"), Path("side.png")]`。蒙版用 `mask=Path("mask.png")`。同一次编辑请统一使用本地文件或字符串素材。请求 `response_format="b64_json"` 时,从 `result.data[0].b64_json` 读取结果。完整服务端响应保存在 `result.raw`。
|
|
33
|
+
|
|
34
|
+
## 异步生成视频
|
|
35
|
+
|
|
36
|
+
下面的程序接收一张参考图和一段音频的公网 URL。视频任务提交后会先打印 ID,等生成完成再打印下载地址。
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
import asyncio
|
|
40
|
+
import sys
|
|
41
|
+
|
|
42
|
+
from dcmarket import AspectRatio, AsyncDCMarket, Resolution
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
async def main(image_url: str, audio_url: str) -> None:
|
|
46
|
+
async with AsyncDCMarket() as dc:
|
|
47
|
+
task = await dc.videos.generate(
|
|
48
|
+
model="doubao-seedance-2-0-260128-max",
|
|
49
|
+
prompt="保持杯身图案,镜头随参考音频的鼓点推进。",
|
|
50
|
+
reference_images=[image_url],
|
|
51
|
+
reference_audios=[audio_url],
|
|
52
|
+
resolution=Resolution.P720,
|
|
53
|
+
aspect_ratio=AspectRatio.R9_16,
|
|
54
|
+
duration=5,
|
|
55
|
+
generate_audio=True,
|
|
56
|
+
)
|
|
57
|
+
print(task.id, flush=True)
|
|
58
|
+
video = await task.wait(timeout=600)
|
|
59
|
+
print(video.url)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
if __name__ == "__main__":
|
|
63
|
+
asyncio.run(main(sys.argv[1], sys.argv[2]))
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
在同一事件循环中可复用一个异步客户端,例如用 `await asyncio.gather(task_a.wait(), task_b.wait())` 等待多个任务。同步视频接口的调用如下。
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from dcmarket import DCMarket
|
|
70
|
+
|
|
71
|
+
with DCMarket() as dc:
|
|
72
|
+
task = dc.videos.generate(
|
|
73
|
+
model="doubao-seedance-2-0-260128-max",
|
|
74
|
+
prompt="清晨的阳光缓慢照进陶艺工作室",
|
|
75
|
+
duration=5,
|
|
76
|
+
)
|
|
77
|
+
print(task.id, flush=True)
|
|
78
|
+
print(task.wait(timeout=600).url)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## 视频参数
|
|
82
|
+
|
|
83
|
+
| 参数 | 用法 |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| `model`、`prompt` | 传平台模型名与提示词;支持素材或草稿输入的模型可省略提示词 |
|
|
86
|
+
| `duration` | 视频时长,单位为秒 |
|
|
87
|
+
| `resolution` | `Resolution.P480`、`P720`、`P1080`,或模型支持的字符串,如 `"720p"` |
|
|
88
|
+
| `aspect_ratio` | `AspectRatio.R16_9`、`R9_16`、`R1_1`、`R4_3`、`R3_4`、`R21_9`、`ADAPTIVE`,或字符串,如 `"9:16"` |
|
|
89
|
+
| `size` | 平台尺寸字段,如 `"1280x720"`;具体档位由模型决定 |
|
|
90
|
+
| `first_frame_image`、`last_frame_image` | 首帧和尾帧,各传一张图的 URL 或模型支持的 data URI |
|
|
91
|
+
| `reference_images`、`reference_videos`、`reference_audios` | 分别传有序的素材 URL 列表。模型按列表顺序引用素材 |
|
|
92
|
+
| `generate_audio`、`seed`、`watermark` | 生成带音频的成片、随机种子和水印开关;按模型能力使用 |
|
|
93
|
+
| `metadata`、`draft_task`、`extra_body` | 模型扩展。使用 `extra_body={"content": [...]}` 可发送原生字段 |
|
|
94
|
+
|
|
95
|
+
## 编辑、延长和恢复视频任务
|
|
96
|
+
|
|
97
|
+
| 同步调用 | 返回结果 |
|
|
98
|
+
| --- | --- |
|
|
99
|
+
| `dc.videos.edit(model=..., video=source_url, prompt=...)` | 视频编辑任务,可指定 `reference_images` |
|
|
100
|
+
| `dc.videos.extend(model=..., video=source_url, prompt=..., duration=5)` | 视频延长任务,`duration` 为新增秒数 |
|
|
101
|
+
| `dc.videos.get(task_id)` | 当前任务,包含 `.id`、`.status`、`.url` 和 `.raw` |
|
|
102
|
+
| `task.wait(timeout=600, poll_interval=5)` | 已完成的视频任务;在创建此任务的客户端关闭前调用 |
|
|
103
|
+
| `dc.videos.content_url(task_id)` | 获取可用于下载成片的链接 |
|
|
104
|
+
|
|
105
|
+
异步客户端对以上调用使用 `await`。等待超时会抛出 `TaskTimeoutError`。保留原任务 ID,稍后用 `dc.videos.get(task_id)` 取回任务并继续 `.wait()`。取消异步等待时,远端已提交的任务会继续处理。
|
|
106
|
+
|
|
107
|
+
异步 `wait(timeout=...)` 会在等待期限到达时取消当前查询。同步客户端在两次查询之间检查期限,也会把剩余时间用于当前请求的网络超时。如果服务器持续缓慢地发送数据,同步调用可能要等当前响应结束才抛出超时异常。
|
|
108
|
+
|
|
109
|
+
任务失败时,`TaskFailedError` 提供 `task_id`、`code` 和 `message`。HTTP 错误通过 `APIError` 提供 `status_code`、`code`、`message` 和可用的 `request_id`。遇到 `NetworkError` 时,创建请求可能已被平台受理,SDK 不会自动重提付费任务。
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "dcmarket"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Sync and asyncio Python clients for the DC Market video and image APIs"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
authors = [{name = "dongchuang"}]
|
|
12
|
+
dependencies = ["httpx>=0.27,<1"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Framework :: AsyncIO",
|
|
15
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
16
|
+
"Topic :: Multimedia :: Graphics",
|
|
17
|
+
"Topic :: Multimedia :: Video",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://market.dcaidc.com"
|
|
23
|
+
|
|
24
|
+
[project.optional-dependencies]
|
|
25
|
+
test = ["pytest>=8", "pytest-cov>=5"]
|
|
26
|
+
|
|
27
|
+
[tool.hatch.build.targets.wheel]
|
|
28
|
+
packages = ["src/dcmarket"]
|
|
29
|
+
|
|
30
|
+
[tool.hatch.build.targets.sdist]
|
|
31
|
+
include = ["/src/dcmarket", "/tests", "/README.md", "/pyproject.toml"]
|
|
32
|
+
|
|
33
|
+
[tool.pytest.ini_options]
|
|
34
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""DC Market Python SDK."""
|
|
2
|
+
|
|
3
|
+
from .client import AsyncDCMarket, DCMarket
|
|
4
|
+
from .errors import APIError, DCMarketError, NetworkError, ProtocolError, TaskFailedError, TaskTimeoutError
|
|
5
|
+
from .images import ImageData, ImageResult
|
|
6
|
+
from .types import AspectRatio, Resolution
|
|
7
|
+
from .videos import AsyncVideoTask, VideoTask
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"APIError", "AspectRatio", "AsyncDCMarket", "DCMarket", "DCMarketError",
|
|
11
|
+
"AsyncVideoTask", "ImageData", "ImageResult", "NetworkError", "ProtocolError",
|
|
12
|
+
"Resolution", "TaskFailedError", "TaskTimeoutError", "VideoTask",
|
|
13
|
+
]
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""HTTP clients for the unified DC Market media API."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import os
|
|
5
|
+
from types import TracebackType
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from .errors import APIError, NetworkError, ProtocolError
|
|
11
|
+
from .images import AsyncImages, Images
|
|
12
|
+
from .videos import AsyncVideos, Videos
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
DEFAULT_BASE_URL = "https://market.dcaidc.com/v1"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _client_options(api_key: str | None, base_url: str, timeout: float) -> dict[str, Any]:
|
|
19
|
+
key = api_key if api_key is not None else os.getenv("DCMARKET_API_KEY")
|
|
20
|
+
if not key or not key.strip():
|
|
21
|
+
raise ValueError("Set DCMARKET_API_KEY or pass api_key to the client.")
|
|
22
|
+
if not math.isfinite(timeout) or timeout <= 0:
|
|
23
|
+
raise ValueError("timeout must be a finite positive number of seconds")
|
|
24
|
+
url = httpx.URL(base_url)
|
|
25
|
+
if url.scheme not in {"http", "https"} or not url.host or url.query or url.fragment or url.userinfo:
|
|
26
|
+
raise ValueError("base_url must be an absolute HTTP(S) API URL without credentials, query or fragment")
|
|
27
|
+
return {
|
|
28
|
+
"base_url": url,
|
|
29
|
+
"headers": {"Authorization": f"Bearer {key.strip()}", "Accept": "application/json"},
|
|
30
|
+
"timeout": timeout,
|
|
31
|
+
"follow_redirects": False,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _check_status(response: httpx.Response) -> None:
|
|
36
|
+
if response.is_success:
|
|
37
|
+
return
|
|
38
|
+
message = response.reason_phrase or "Request failed"
|
|
39
|
+
code = None
|
|
40
|
+
try:
|
|
41
|
+
body = response.json()
|
|
42
|
+
except (ValueError, UnicodeError):
|
|
43
|
+
body = None
|
|
44
|
+
if isinstance(body, dict):
|
|
45
|
+
error = body.get("error", body)
|
|
46
|
+
if isinstance(error, dict):
|
|
47
|
+
message = str(error.get("message") or message)
|
|
48
|
+
if error.get("code") is not None:
|
|
49
|
+
code = str(error["code"])
|
|
50
|
+
elif isinstance(error, str) and error:
|
|
51
|
+
message = error
|
|
52
|
+
raise APIError(response.status_code, message, code=code,
|
|
53
|
+
request_id=response.headers.get("x-request-id"))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _json_object(response: httpx.Response) -> dict[str, Any]:
|
|
57
|
+
_check_status(response)
|
|
58
|
+
try:
|
|
59
|
+
data = response.json()
|
|
60
|
+
except (ValueError, UnicodeError) as exc:
|
|
61
|
+
raise ProtocolError("Expected a JSON response") from exc
|
|
62
|
+
if not isinstance(data, dict):
|
|
63
|
+
raise ProtocolError("Expected a JSON object")
|
|
64
|
+
return data
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _content_location(response: httpx.Response) -> str:
|
|
68
|
+
if response.status_code not in (301, 302, 303, 307, 308):
|
|
69
|
+
_check_status(response)
|
|
70
|
+
raise ProtocolError("Expected a redirect to the video content")
|
|
71
|
+
location = response.headers.get("location")
|
|
72
|
+
if not location:
|
|
73
|
+
raise ProtocolError("Missing video content URL in redirect")
|
|
74
|
+
try:
|
|
75
|
+
url = response.url.join(location)
|
|
76
|
+
except httpx.InvalidURL as exc:
|
|
77
|
+
raise ProtocolError("Invalid video content URL") from exc
|
|
78
|
+
if url.scheme not in {"http", "https"} or not url.host or url.userinfo:
|
|
79
|
+
raise ProtocolError("Expected an HTTP(S) video content URL")
|
|
80
|
+
return str(url)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class _ClientTimeout:
|
|
84
|
+
_timeout: float
|
|
85
|
+
|
|
86
|
+
def _poll_timeout(self, remaining: float) -> float:
|
|
87
|
+
return min(self._timeout, remaining)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class DCMarket(_ClientTimeout):
|
|
91
|
+
"""Synchronous DC Market client. Reuse it across requests or use a with block."""
|
|
92
|
+
|
|
93
|
+
def __init__(self, api_key: str | None = None, *, base_url: str = DEFAULT_BASE_URL,
|
|
94
|
+
timeout: float = 300.0, transport: httpx.BaseTransport | None = None) -> None:
|
|
95
|
+
self._timeout = timeout
|
|
96
|
+
self._http = httpx.Client(transport=transport, **_client_options(api_key, base_url, timeout))
|
|
97
|
+
self.images = Images(self)
|
|
98
|
+
self.videos = Videos(self)
|
|
99
|
+
|
|
100
|
+
def _send(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
|
|
101
|
+
try:
|
|
102
|
+
return self._http.request(method, path, **kwargs)
|
|
103
|
+
except httpx.RequestError as exc:
|
|
104
|
+
raise NetworkError(f"{method} {path} failed ({type(exc).__name__})") from exc
|
|
105
|
+
|
|
106
|
+
def _request(self, method: str, path: str, **kwargs: Any) -> dict[str, Any]:
|
|
107
|
+
return _json_object(self._send(method, path, **kwargs))
|
|
108
|
+
|
|
109
|
+
def _redirect_url(self, path: str) -> str:
|
|
110
|
+
return _content_location(self._send("GET", path))
|
|
111
|
+
|
|
112
|
+
def close(self) -> None:
|
|
113
|
+
self._http.close()
|
|
114
|
+
|
|
115
|
+
def __enter__(self) -> "DCMarket":
|
|
116
|
+
return self
|
|
117
|
+
|
|
118
|
+
def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None,
|
|
119
|
+
tb: TracebackType | None) -> None:
|
|
120
|
+
self.close()
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class AsyncDCMarket(_ClientTimeout):
|
|
124
|
+
"""Asyncio DC Market client. Share it between tasks on the same event loop."""
|
|
125
|
+
|
|
126
|
+
def __init__(self, api_key: str | None = None, *, base_url: str = DEFAULT_BASE_URL,
|
|
127
|
+
timeout: float = 300.0, transport: httpx.AsyncBaseTransport | None = None) -> None:
|
|
128
|
+
self._timeout = timeout
|
|
129
|
+
self._http = httpx.AsyncClient(transport=transport, **_client_options(api_key, base_url, timeout))
|
|
130
|
+
self.images = AsyncImages(self)
|
|
131
|
+
self.videos = AsyncVideos(self)
|
|
132
|
+
|
|
133
|
+
async def _send(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
|
|
134
|
+
try:
|
|
135
|
+
return await self._http.request(method, path, **kwargs)
|
|
136
|
+
except httpx.RequestError as exc:
|
|
137
|
+
raise NetworkError(f"{method} {path} failed ({type(exc).__name__})") from exc
|
|
138
|
+
|
|
139
|
+
async def _request(self, method: str, path: str, **kwargs: Any) -> dict[str, Any]:
|
|
140
|
+
return _json_object(await self._send(method, path, **kwargs))
|
|
141
|
+
|
|
142
|
+
async def _redirect_url(self, path: str) -> str:
|
|
143
|
+
return _content_location(await self._send("GET", path))
|
|
144
|
+
|
|
145
|
+
async def aclose(self) -> None:
|
|
146
|
+
await self._http.aclose()
|
|
147
|
+
|
|
148
|
+
async def __aenter__(self) -> "AsyncDCMarket":
|
|
149
|
+
return self
|
|
150
|
+
|
|
151
|
+
async def __aexit__(self, exc_type: type[BaseException] | None, exc: BaseException | None,
|
|
152
|
+
tb: TracebackType | None) -> None:
|
|
153
|
+
await self.aclose()
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Exceptions shared by the synchronous and asynchronous clients."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class DCMarketError(Exception):
|
|
7
|
+
"""Base class for DC Market request and task errors."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class APIError(DCMarketError):
|
|
11
|
+
"""The API returned an unsuccessful HTTP status."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, status_code: int, message: str, *, code: str | None = None,
|
|
14
|
+
request_id: str | None = None) -> None:
|
|
15
|
+
self.status_code = status_code
|
|
16
|
+
self.message = message
|
|
17
|
+
self.code = code
|
|
18
|
+
self.request_id = request_id
|
|
19
|
+
super().__init__(f"HTTP {status_code}: {message}")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class NetworkError(DCMarketError):
|
|
23
|
+
"""A connection or network operation failed. A submitted job may still exist."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ProtocolError(DCMarketError):
|
|
27
|
+
"""The API returned an unexpected successful response."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TaskFailedError(DCMarketError):
|
|
31
|
+
"""The server reported a failed video task."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, task: dict[str, Any]) -> None:
|
|
34
|
+
self.task = task
|
|
35
|
+
self.task_id = task.get("id")
|
|
36
|
+
error = task.get("error")
|
|
37
|
+
self.code = error.get("code") if isinstance(error, dict) else None
|
|
38
|
+
self.message = error.get("message") if isinstance(error, dict) else error
|
|
39
|
+
super().__init__(f"Video task {self.task_id} failed: {self.message or 'unknown error'}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class TaskTimeoutError(DCMarketError, TimeoutError):
|
|
43
|
+
"""Local polling expired. The same task can be retrieved later."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, task_id: str) -> None:
|
|
46
|
+
self.task_id = task_id
|
|
47
|
+
super().__init__(f"Timed out waiting for video task {task_id}")
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Image generation and editing through the unified image API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import mimetypes
|
|
7
|
+
from collections.abc import AsyncIterator, Callable, Sequence
|
|
8
|
+
from contextlib import ExitStack
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import TYPE_CHECKING, Any, TypeVar
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from .errors import ProtocolError
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from .client import AsyncDCMarket, DCMarket
|
|
19
|
+
|
|
20
|
+
ImageInput = str | Path | Sequence[str | Path]
|
|
21
|
+
_T = TypeVar("_T")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class ImageData:
|
|
26
|
+
url: str | None = None
|
|
27
|
+
b64_json: str | None = None
|
|
28
|
+
mime_type: str | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ImageResult:
|
|
32
|
+
def __init__(self, raw: dict[str, Any]):
|
|
33
|
+
items = raw.get("data")
|
|
34
|
+
if not isinstance(items, list) or not items:
|
|
35
|
+
raise ProtocolError("Image response has no data array or images")
|
|
36
|
+
self.raw = raw
|
|
37
|
+
self.data: list[ImageData] = []
|
|
38
|
+
for item in items:
|
|
39
|
+
if not isinstance(item, dict):
|
|
40
|
+
raise ProtocolError("Invalid image data item")
|
|
41
|
+
url, b64 = item.get("url"), item.get("b64_json")
|
|
42
|
+
if not (isinstance(url, str) and url or isinstance(b64, str) and b64):
|
|
43
|
+
raise ProtocolError("Image data item has no URL or base64 content")
|
|
44
|
+
self.data.append(ImageData(url, b64, item.get("mime_type")))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _payload(model: str, prompt: str, options: dict[str, Any]) -> dict[str, Any]:
|
|
48
|
+
if not isinstance(model, str) or not model.strip():
|
|
49
|
+
raise ValueError("model must be a nonempty string")
|
|
50
|
+
if not isinstance(prompt, str) or not prompt.strip():
|
|
51
|
+
raise ValueError("prompt must be a nonempty string")
|
|
52
|
+
return {"model": model, "prompt": prompt, **{k: v for k, v in options.items() if v is not None}}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _edit_inputs(
|
|
56
|
+
payload: dict[str, Any], image: ImageInput, mask: str | Path | None
|
|
57
|
+
) -> list[tuple[str, Path]]:
|
|
58
|
+
references: list[str | Path]
|
|
59
|
+
if isinstance(image, (str, Path)):
|
|
60
|
+
references = [image]
|
|
61
|
+
elif isinstance(image, Sequence) and not isinstance(image, (bytes, bytearray)):
|
|
62
|
+
references = list(image)
|
|
63
|
+
else:
|
|
64
|
+
raise TypeError("image must be a string, a Path, or a sequence of images")
|
|
65
|
+
if not references:
|
|
66
|
+
raise ValueError("image must include at least one reference")
|
|
67
|
+
parts = [("image", item) for item in references]
|
|
68
|
+
if mask is not None:
|
|
69
|
+
parts.append(("mask", mask))
|
|
70
|
+
urls = [item for _, item in parts if isinstance(item, str)]
|
|
71
|
+
if len(urls) == len(parts):
|
|
72
|
+
if any(not item.strip() for item in urls):
|
|
73
|
+
raise ValueError("image and mask references must be nonempty")
|
|
74
|
+
payload["image"] = image if isinstance(image, str) else references
|
|
75
|
+
if mask is not None:
|
|
76
|
+
payload["mask"] = mask
|
|
77
|
+
return []
|
|
78
|
+
paths = [(name, item) for name, item in parts if isinstance(item, Path)]
|
|
79
|
+
if len(paths) != len(parts):
|
|
80
|
+
raise TypeError("use only URL/base64 strings or only Path objects for image and mask")
|
|
81
|
+
return paths
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _open_upload(stack: ExitStack, payload: dict[str, Any], parts: list[tuple[str, Path]]) -> httpx.Request:
|
|
85
|
+
files = []
|
|
86
|
+
for name, path in parts:
|
|
87
|
+
stream = stack.enter_context(path.open("rb"))
|
|
88
|
+
mime = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
|
|
89
|
+
files.append((name, (path.name, stream, mime)))
|
|
90
|
+
return httpx.Request("POST", "images/edits", data=payload, files=files)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
async def _file_io(operation: Callable[..., _T], *args: Any) -> _T:
|
|
94
|
+
# A cancelled executor future can leave the worker reading a file we are about to close.
|
|
95
|
+
worker = asyncio.create_task(asyncio.to_thread(operation, *args))
|
|
96
|
+
try:
|
|
97
|
+
return await asyncio.shield(worker)
|
|
98
|
+
except asyncio.CancelledError:
|
|
99
|
+
while not worker.done():
|
|
100
|
+
try:
|
|
101
|
+
await asyncio.shield(worker)
|
|
102
|
+
except asyncio.CancelledError:
|
|
103
|
+
continue
|
|
104
|
+
raise
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
async def _chunks(request: httpx.Request) -> AsyncIterator[bytes]:
|
|
108
|
+
assert isinstance(request.stream, httpx.SyncByteStream)
|
|
109
|
+
chunks = iter(request.stream)
|
|
110
|
+
while (chunk := await _file_io(next, chunks, None)) is not None:
|
|
111
|
+
yield chunk
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class Images:
|
|
115
|
+
def __init__(self, client: DCMarket):
|
|
116
|
+
self._client = client
|
|
117
|
+
|
|
118
|
+
def generate(self, *, model: str, prompt: str, **options: Any) -> ImageResult:
|
|
119
|
+
"""Generate images and return URLs or base64 content."""
|
|
120
|
+
payload = _payload(model, prompt, options)
|
|
121
|
+
return ImageResult(self._client._request("POST", "images/generations", json=payload))
|
|
122
|
+
|
|
123
|
+
def edit(
|
|
124
|
+
self, *, model: str, prompt: str, image: ImageInput,
|
|
125
|
+
mask: str | Path | None = None, **options: Any,
|
|
126
|
+
) -> ImageResult:
|
|
127
|
+
"""Edit URL/base64 strings or upload local Path objects, including an optional mask."""
|
|
128
|
+
payload = _payload(model, prompt, options)
|
|
129
|
+
parts = _edit_inputs(payload, image, mask)
|
|
130
|
+
if not parts:
|
|
131
|
+
return ImageResult(self._client._request("POST", "images/edits", json=payload))
|
|
132
|
+
with ExitStack() as stack:
|
|
133
|
+
upload = _open_upload(stack, payload, parts)
|
|
134
|
+
raw = self._client._request("POST", "images/edits", headers=upload.headers, content=upload.stream)
|
|
135
|
+
return ImageResult(raw)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class AsyncImages:
|
|
139
|
+
def __init__(self, client: AsyncDCMarket):
|
|
140
|
+
self._client = client
|
|
141
|
+
|
|
142
|
+
async def generate(self, *, model: str, prompt: str, **options: Any) -> ImageResult:
|
|
143
|
+
"""Generate images and return URLs or base64 content."""
|
|
144
|
+
payload = _payload(model, prompt, options)
|
|
145
|
+
return ImageResult(await self._client._request("POST", "images/generations", json=payload))
|
|
146
|
+
|
|
147
|
+
async def edit(
|
|
148
|
+
self, *, model: str, prompt: str, image: ImageInput,
|
|
149
|
+
mask: str | Path | None = None, **options: Any,
|
|
150
|
+
) -> ImageResult:
|
|
151
|
+
"""Edit URL/base64 strings or stream local files with nonblocking disk reads."""
|
|
152
|
+
payload = _payload(model, prompt, options)
|
|
153
|
+
parts = _edit_inputs(payload, image, mask)
|
|
154
|
+
if not parts:
|
|
155
|
+
return ImageResult(await self._client._request("POST", "images/edits", json=payload))
|
|
156
|
+
with ExitStack() as stack:
|
|
157
|
+
upload = await _file_io(_open_upload, stack, payload, parts)
|
|
158
|
+
raw = await self._client._request(
|
|
159
|
+
"POST", "images/edits", headers=upload.headers, content=_chunks(upload)
|
|
160
|
+
)
|
|
161
|
+
return ImageResult(raw)
|
|
File without changes
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""String values accepted by the unified video endpoint."""
|
|
2
|
+
|
|
3
|
+
from enum import Enum
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Resolution(str, Enum):
|
|
7
|
+
P480 = "480p"
|
|
8
|
+
P720 = "720p"
|
|
9
|
+
P1080 = "1080p"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AspectRatio(str, Enum):
|
|
13
|
+
R16_9 = "16:9"
|
|
14
|
+
R9_16 = "9:16"
|
|
15
|
+
R1_1 = "1:1"
|
|
16
|
+
R4_3 = "4:3"
|
|
17
|
+
R3_4 = "3:4"
|
|
18
|
+
R21_9 = "21:9"
|
|
19
|
+
ADAPTIVE = "adaptive"
|