@chad.dev/dsh-adclip 0.0.0-stage → 0.1.0
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.
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +28 -2
- package/client.js +2157 -0
- package/cordis.patch.yml +10 -0
- package/engine/requirements.txt +9 -0
- package/engine/src/adclip/__init__.py +0 -0
- package/engine/src/adclip/api.py +676 -0
- package/engine/src/adclip/image_params.py +64 -0
- package/engine/src/adclip/intents.py +190 -0
- package/engine/src/adclip/llm.py +142 -0
- package/engine/src/adclip/media/__init__.py +0 -0
- package/engine/src/adclip/media/asr.py +79 -0
- package/engine/src/adclip/media/ffmpeg.py +294 -0
- package/engine/src/adclip/media/stitch.py +124 -0
- package/engine/src/adclip/media/subtitles.py +45 -0
- package/engine/src/adclip/media/vision.py +105 -0
- package/engine/src/adclip/models.py +127 -0
- package/engine/src/adclip/params.py +363 -0
- package/engine/src/adclip/personas.py +60 -0
- package/engine/src/adclip/pipeline/__init__.py +0 -0
- package/engine/src/adclip/pipeline/analyze.py +133 -0
- package/engine/src/adclip/pipeline/generate.py +201 -0
- package/engine/src/adclip/pipeline/image_runner.py +131 -0
- package/engine/src/adclip/pipeline/persona.py +56 -0
- package/engine/src/adclip/pipeline/post.py +33 -0
- package/engine/src/adclip/pipeline/qa.py +41 -0
- package/engine/src/adclip/pipeline/replace.py +191 -0
- package/engine/src/adclip/pipeline/runner.py +138 -0
- package/engine/src/adclip/pipeline/script.py +226 -0
- package/engine/src/adclip/pipeline/segment.py +87 -0
- package/engine/src/adclip/providers/__init__.py +0 -0
- package/engine/src/adclip/providers/ark.py +122 -0
- package/engine/src/adclip/providers/base.py +30 -0
- package/engine/src/adclip/providers/discovery.py +56 -0
- package/engine/src/adclip/providers/kling.py +101 -0
- package/engine/src/adclip/providers/minimax.py +155 -0
- package/engine/src/adclip/providers/minimax_image.py +86 -0
- package/engine/src/adclip/settings.py +109 -0
- package/engine/src/adclip/store.py +378 -0
- package/host/dsh.js +60 -0
- package/host/engine.js +265 -0
- package/host/proxy.js +142 -0
- package/host/supervisor.js +251 -0
- package/icon.svg +6 -0
- package/index.js +39 -0
- package/locale/en.json +12 -0
- package/locale/zh.json +12 -0
- package/package.json +47 -4
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Minimal Volcengine Ark Seedance adapter (native audio).
|
|
2
|
+
|
|
3
|
+
This is intentionally small: create a content-generation task, poll it, download
|
|
4
|
+
the result. It is implemented against the official Ark REST shape used by the
|
|
5
|
+
existing AdPlus tooling, but is marked unverified until a real key is available.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import mimetypes
|
|
11
|
+
import os
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from .base import Provider, ProviderError, ProviderNotConfigured
|
|
18
|
+
|
|
19
|
+
BASE_URL = os.environ.get("ARK_BASE_URL", "https://ark.cn-beijing.volces.com/api/v3")
|
|
20
|
+
MODELS = {
|
|
21
|
+
"ark.seedance-2.5": "doubao-seedance-2-5-260628",
|
|
22
|
+
"ark.seedance-2.0": "doubao-seedance-2-0-260128",
|
|
23
|
+
"ark.seedance-2.0-mini": "doubao-seedance-2-0-mini-260615",
|
|
24
|
+
"ark.seedance-2.0-fast": "doubao-seedance-2-0-fast-260128",
|
|
25
|
+
}
|
|
26
|
+
MODEL_ENV = {
|
|
27
|
+
"ark.seedance-2.5": "ARK_MODEL_SEEDANCE_2_5",
|
|
28
|
+
"ark.seedance-2.0": "ARK_MODEL_SEEDANCE_2_0",
|
|
29
|
+
"ark.seedance-2.0-mini": "ARK_MODEL_SEEDANCE_2_0_MINI",
|
|
30
|
+
"ark.seedance-2.0-fast": "ARK_MODEL_SEEDANCE_2_0_FAST",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _model_id(model: str) -> str:
|
|
35
|
+
env_name = MODEL_ENV.get(model)
|
|
36
|
+
return (os.environ.get(env_name, "").strip() if env_name else "") or MODELS.get(model, "")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _api_key() -> str:
|
|
40
|
+
key = os.environ.get("ARK_API_KEY", "").strip()
|
|
41
|
+
if key.lower().startswith("bearer "):
|
|
42
|
+
key = key[7:].strip()
|
|
43
|
+
return key
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _data_uri(path: Path) -> str:
|
|
47
|
+
mime = mimetypes.guess_type(path.name)[0] or "image/png"
|
|
48
|
+
return f"data:{mime};base64,{base64.b64encode(path.read_bytes()).decode('ascii')}"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class ArkProvider(Provider):
|
|
52
|
+
id = "ark"
|
|
53
|
+
|
|
54
|
+
def generate(
|
|
55
|
+
self,
|
|
56
|
+
prompt: str,
|
|
57
|
+
*,
|
|
58
|
+
images: list[Path] | None = None,
|
|
59
|
+
duration: int = 8,
|
|
60
|
+
resolution: str = "720p",
|
|
61
|
+
aspect: str = "9:16",
|
|
62
|
+
model: str = "ark.seedance-2.5",
|
|
63
|
+
output: Path,
|
|
64
|
+
) -> Path:
|
|
65
|
+
key = _api_key()
|
|
66
|
+
if not key:
|
|
67
|
+
raise ProviderNotConfigured("未配置 ARK_API_KEY")
|
|
68
|
+
model_id = _model_id(model)
|
|
69
|
+
if model_id is None:
|
|
70
|
+
raise ProviderError(f"未知 Ark 模型:{model}")
|
|
71
|
+
content: list[dict] = [{"type": "text", "text": prompt}]
|
|
72
|
+
for path in (images or [])[:9]:
|
|
73
|
+
content.append({
|
|
74
|
+
"type": "image_url",
|
|
75
|
+
"image_url": {"url": _data_uri(path)},
|
|
76
|
+
"role": "reference_image",
|
|
77
|
+
})
|
|
78
|
+
payload = {
|
|
79
|
+
"model": model_id,
|
|
80
|
+
"content": content,
|
|
81
|
+
"duration": max(4, min(30, int(duration))),
|
|
82
|
+
"resolution": resolution,
|
|
83
|
+
"ratio": aspect,
|
|
84
|
+
"generate_audio": True,
|
|
85
|
+
"watermark": False,
|
|
86
|
+
"return_last_frame": False,
|
|
87
|
+
}
|
|
88
|
+
headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
|
|
89
|
+
try:
|
|
90
|
+
with httpx.Client(timeout=httpx.Timeout(60.0, connect=15.0)) as client:
|
|
91
|
+
created = client.post(f"{BASE_URL}/contents/generations/tasks", headers=headers, json=payload)
|
|
92
|
+
if created.status_code >= 400:
|
|
93
|
+
raise ProviderError(f"Ark 创建任务失败 HTTP {created.status_code}: {created.text[:300]}")
|
|
94
|
+
task_id = created.json().get("id")
|
|
95
|
+
if not task_id:
|
|
96
|
+
raise ProviderError("Ark 没有返回 task id")
|
|
97
|
+
deadline = time.monotonic() + 1500
|
|
98
|
+
while time.monotonic() < deadline:
|
|
99
|
+
time.sleep(3)
|
|
100
|
+
status_res = client.get(f"{BASE_URL}/contents/generations/tasks/{task_id}", headers=headers)
|
|
101
|
+
if status_res.status_code >= 400:
|
|
102
|
+
raise ProviderError(f"Ark 查询失败 HTTP {status_res.status_code}: {status_res.text[:300]}")
|
|
103
|
+
task = status_res.json()
|
|
104
|
+
status = str(task.get("status") or "").lower()
|
|
105
|
+
if status in {"failed", "cancelled", "expired"}:
|
|
106
|
+
raise ProviderError(f"Ark 任务 {status}: {task.get('error') or task}")
|
|
107
|
+
if status == "succeeded":
|
|
108
|
+
url = ((task.get("content") or {}).get("video_url"))
|
|
109
|
+
if not url:
|
|
110
|
+
raise ProviderError("Ark 成功但没有 video_url")
|
|
111
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
112
|
+
with client.stream("GET", url, timeout=120.0) as download:
|
|
113
|
+
download.raise_for_status()
|
|
114
|
+
with output.open("wb") as handle:
|
|
115
|
+
for chunk in download.iter_bytes():
|
|
116
|
+
handle.write(chunk)
|
|
117
|
+
if not output.is_file() or output.stat().st_size == 0:
|
|
118
|
+
raise ProviderError("Ark 下载结果为空")
|
|
119
|
+
return output
|
|
120
|
+
raise ProviderError("Ark 任务超时")
|
|
121
|
+
except httpx.HTTPError as exc:
|
|
122
|
+
raise ProviderError(f"Ark 网络错误:{exc}") from exc
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Provider seam shared by real adapters."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ProviderError(RuntimeError):
|
|
9
|
+
"""A provider call failed with a user-actionable reason."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ProviderNotConfigured(ProviderError):
|
|
13
|
+
"""The provider key or adapter is not ready."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Provider:
|
|
17
|
+
id = "base"
|
|
18
|
+
|
|
19
|
+
def generate(
|
|
20
|
+
self,
|
|
21
|
+
prompt: str,
|
|
22
|
+
*,
|
|
23
|
+
images: list[Path] | None = None,
|
|
24
|
+
duration: int = 8,
|
|
25
|
+
resolution: str = "720p",
|
|
26
|
+
aspect: str = "9:16",
|
|
27
|
+
model: str = "",
|
|
28
|
+
output: Path,
|
|
29
|
+
) -> Path:
|
|
30
|
+
raise NotImplementedError
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Best-effort vendor model discovery.
|
|
2
|
+
|
|
3
|
+
Video adapters still own the list of models they can actually call. Vendor APIs
|
|
4
|
+
do not consistently expose video models: MiniMax's /v1/models returns its text
|
|
5
|
+
models, and Kling has no public model-list endpoint. This module therefore
|
|
6
|
+
discovers what the vendor exposes and leaves the adapter catalogue authoritative
|
|
7
|
+
for video generation.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from .ark import BASE_URL as ARK_BASE
|
|
17
|
+
|
|
18
|
+
MINIMAX_BASE = os.environ.get("MINIMAX_API_BASE", "https://api.minimaxi.com").rstrip("/")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _models_from_payload(payload: Any) -> list[str]:
|
|
22
|
+
rows = []
|
|
23
|
+
if isinstance(payload, dict):
|
|
24
|
+
rows = payload.get("data") or payload.get("models") or []
|
|
25
|
+
if not isinstance(rows, list):
|
|
26
|
+
return []
|
|
27
|
+
out = []
|
|
28
|
+
for row in rows:
|
|
29
|
+
if isinstance(row, str):
|
|
30
|
+
out.append(row)
|
|
31
|
+
elif isinstance(row, dict):
|
|
32
|
+
value = row.get("id") or row.get("model") or row.get("name")
|
|
33
|
+
if value:
|
|
34
|
+
out.append(str(value))
|
|
35
|
+
return sorted(set(out))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _get(url: str, key: str) -> dict[str, Any]:
|
|
39
|
+
if not key:
|
|
40
|
+
return {"ok": False, "models": [], "error": "未配置 API key", "source": url}
|
|
41
|
+
try:
|
|
42
|
+
with httpx.Client(timeout=httpx.Timeout(20.0, connect=8.0)) as client:
|
|
43
|
+
response = client.get(url, headers={"Authorization": f"Bearer {key}"})
|
|
44
|
+
if response.status_code >= 400:
|
|
45
|
+
return {"ok": False, "models": [], "error": f"HTTP {response.status_code}: {response.text[:180]}", "source": url}
|
|
46
|
+
return {"ok": True, "models": _models_from_payload(response.json()), "error": "", "source": url}
|
|
47
|
+
except Exception as exc: # noqa: BLE001
|
|
48
|
+
return {"ok": False, "models": [], "error": f"{type(exc).__name__}: {exc}"[:240], "source": url}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def discover() -> dict[str, Any]:
|
|
52
|
+
minimax = _get(f"{MINIMAX_BASE}/v1/models", os.environ.get("MINIMAX_API_KEY", "").strip())
|
|
53
|
+
ark = _get(f"{ARK_BASE}/models", os.environ.get("ARK_API_KEY", "").strip())
|
|
54
|
+
# Kling's classic API has no model-list route; adapter remains authoritative.
|
|
55
|
+
kling = {"ok": False, "models": [], "error": "Kling 未提供模型列表接口;使用适配器支持列表", "source": "adapter"}
|
|
56
|
+
return {"minimax": minimax, "ark": ark, "kling": kling}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Minimal Kling official video adapter.
|
|
2
|
+
|
|
3
|
+
Uses the classic `/v1/videos/text2video` or `/v1/videos/image2video` task API,
|
|
4
|
+
with `sound=on` for native dialogue/audio on supported models. Local images are
|
|
5
|
+
sent as raw base64, matching the official classic API shape.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import os
|
|
11
|
+
import time
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from .base import Provider, ProviderError, ProviderNotConfigured
|
|
17
|
+
|
|
18
|
+
BASE_URL = os.environ.get("KLING_API_BASE_URL", "https://api-singapore.klingai.com").rstrip("/")
|
|
19
|
+
MODELS = {"kling.v3": "kling-v3", "kling.v2.6": "kling-v2-6"}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _api_key() -> str:
|
|
23
|
+
return os.environ.get("KLING_API_KEY", "").strip()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _raw_base64(path: Path) -> str:
|
|
27
|
+
return base64.b64encode(path.read_bytes()).decode("ascii")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class KlingProvider(Provider):
|
|
31
|
+
id = "kling"
|
|
32
|
+
|
|
33
|
+
def generate(
|
|
34
|
+
self,
|
|
35
|
+
prompt: str,
|
|
36
|
+
*,
|
|
37
|
+
images: list[Path] | None = None,
|
|
38
|
+
duration: int = 8,
|
|
39
|
+
resolution: str = "720p",
|
|
40
|
+
aspect: str = "9:16",
|
|
41
|
+
model: str = "kling.v3",
|
|
42
|
+
output: Path,
|
|
43
|
+
) -> Path:
|
|
44
|
+
key = _api_key()
|
|
45
|
+
if not key:
|
|
46
|
+
raise ProviderNotConfigured("未配置 KLING_API_KEY")
|
|
47
|
+
model_name = MODELS.get(model)
|
|
48
|
+
if not model_name:
|
|
49
|
+
raise ProviderError(f"未知 Kling 模型:{model}")
|
|
50
|
+
headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
|
|
51
|
+
duration_s = str(5 if duration <= 5 else 10)
|
|
52
|
+
mode = "pro" if resolution == "1080p" else "std"
|
|
53
|
+
payload = {
|
|
54
|
+
"model_name": model_name,
|
|
55
|
+
"prompt": prompt,
|
|
56
|
+
"duration": duration_s,
|
|
57
|
+
"mode": mode,
|
|
58
|
+
"sound": "on",
|
|
59
|
+
"aspect_ratio": aspect,
|
|
60
|
+
"negative_prompt": "字幕, 水印, logo, 文字",
|
|
61
|
+
}
|
|
62
|
+
if images:
|
|
63
|
+
payload["image"] = _raw_base64(images[0])
|
|
64
|
+
path = "/v1/videos/image2video"
|
|
65
|
+
else:
|
|
66
|
+
path = "/v1/videos/text2video"
|
|
67
|
+
try:
|
|
68
|
+
with httpx.Client(timeout=httpx.Timeout(60.0, connect=15.0)) as client:
|
|
69
|
+
created = client.post(f"{BASE_URL}{path}", headers=headers, json=payload)
|
|
70
|
+
if created.status_code >= 400:
|
|
71
|
+
raise ProviderError(f"Kling 创建任务失败 HTTP {created.status_code}: {created.text[:300]}")
|
|
72
|
+
body = created.json()
|
|
73
|
+
task_id = ((body.get("data") or {}).get("task_id"))
|
|
74
|
+
if not task_id:
|
|
75
|
+
raise ProviderError(f"Kling 没有返回 task_id: {body}")
|
|
76
|
+
deadline = time.monotonic() + 1500
|
|
77
|
+
while time.monotonic() < deadline:
|
|
78
|
+
time.sleep(4)
|
|
79
|
+
status_res = client.get(f"{BASE_URL}{path}/{task_id}", headers=headers)
|
|
80
|
+
if status_res.status_code >= 400:
|
|
81
|
+
raise ProviderError(f"Kling 查询失败 HTTP {status_res.status_code}: {status_res.text[:300]}")
|
|
82
|
+
task = (status_res.json().get("data") or {})
|
|
83
|
+
status = str(task.get("task_status") or task.get("status") or "").lower()
|
|
84
|
+
if status in {"failed", "failure"}:
|
|
85
|
+
raise ProviderError(f"Kling 任务失败: {task.get('task_status_msg') or task}")
|
|
86
|
+
if status in {"succeed", "succeeded", "success"}:
|
|
87
|
+
videos = ((task.get("task_result") or {}).get("videos") or [])
|
|
88
|
+
if not videos or not videos[0].get("url"):
|
|
89
|
+
raise ProviderError("Kling 成功但没有视频 URL")
|
|
90
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
91
|
+
with client.stream("GET", videos[0]["url"], timeout=180.0) as download:
|
|
92
|
+
download.raise_for_status()
|
|
93
|
+
with output.open("wb") as handle:
|
|
94
|
+
for chunk in download.iter_bytes():
|
|
95
|
+
handle.write(chunk)
|
|
96
|
+
if not output.is_file() or output.stat().st_size == 0:
|
|
97
|
+
raise ProviderError("Kling 下载结果为空")
|
|
98
|
+
return output
|
|
99
|
+
raise ProviderError("Kling 任务超时")
|
|
100
|
+
except httpx.HTTPError as exc:
|
|
101
|
+
raise ProviderError(f"Kling 网络错误:{exc}") from exc
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""MiniMax video adapter (Hailuo v1 + H3 v2).
|
|
2
|
+
|
|
3
|
+
The v1 Hailuo path is the low-cost smoke-test path. H3 uses the v2
|
|
4
|
+
content-generation task API. Native dialogue is not claimed until a real
|
|
5
|
+
bake-off confirms it; the catalogue marks the current Hailuo entry accordingly.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import mimetypes
|
|
11
|
+
import os
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from .base import Provider, ProviderError, ProviderNotConfigured
|
|
18
|
+
|
|
19
|
+
CN_BASE = os.environ.get("MINIMAX_API_BASE", "https://api.minimaxi.com").rstrip("/")
|
|
20
|
+
GLOBAL_BASE = os.environ.get("MINIMAX_GLOBAL_BASE", "https://api.minimax.io").rstrip("/")
|
|
21
|
+
MODELS = {
|
|
22
|
+
"minimax.hailuo-2.3-fast": ("MiniMax-Hailuo-2.3-Fast", "v1"),
|
|
23
|
+
"minimax.h3": ("MiniMax-H3", "v2"),
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _api_key() -> str:
|
|
28
|
+
return os.environ.get("MINIMAX_API_KEY", "").strip()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _data_uri(path: Path) -> str:
|
|
32
|
+
mime = mimetypes.guess_type(path.name)[0] or "image/png"
|
|
33
|
+
return f"data:{mime};base64,{base64.b64encode(path.read_bytes()).decode('ascii')}"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _error_message(payload: dict) -> str:
|
|
37
|
+
base = payload.get("base_resp") or {}
|
|
38
|
+
return str(base.get("status_msg") or payload.get("message") or payload.get("error") or payload)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class MiniMaxProvider(Provider):
|
|
42
|
+
id = "minimax"
|
|
43
|
+
|
|
44
|
+
def generate(
|
|
45
|
+
self,
|
|
46
|
+
prompt: str,
|
|
47
|
+
*,
|
|
48
|
+
images: list[Path] | None = None,
|
|
49
|
+
duration: int = 6,
|
|
50
|
+
resolution: str = "768P",
|
|
51
|
+
aspect: str = "9:16",
|
|
52
|
+
model: str = "minimax.hailuo-2.3-fast",
|
|
53
|
+
output: Path,
|
|
54
|
+
) -> Path:
|
|
55
|
+
key = _api_key()
|
|
56
|
+
if not key:
|
|
57
|
+
raise ProviderNotConfigured("未配置 MINIMAX_API_KEY")
|
|
58
|
+
if model not in MODELS:
|
|
59
|
+
raise ProviderError(f"未知 MiniMax 模型:{model}")
|
|
60
|
+
model_name, api = MODELS[model]
|
|
61
|
+
headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
|
|
62
|
+
errors = []
|
|
63
|
+
for base in (CN_BASE, GLOBAL_BASE):
|
|
64
|
+
try:
|
|
65
|
+
with httpx.Client(timeout=httpx.Timeout(60.0, connect=15.0)) as client:
|
|
66
|
+
if api == "v2":
|
|
67
|
+
payload = {
|
|
68
|
+
"model": model_name,
|
|
69
|
+
"content": [{"type": "text", "text": prompt}],
|
|
70
|
+
"resolution": "2K",
|
|
71
|
+
"duration": max(4, min(15, int(duration))),
|
|
72
|
+
"ratio": aspect,
|
|
73
|
+
}
|
|
74
|
+
created = client.post(f"{base}/v2/video_generation", headers=headers, json=payload)
|
|
75
|
+
if created.status_code >= 400:
|
|
76
|
+
raise ProviderError(f"MiniMax 创建失败 HTTP {created.status_code}: {created.text[:300]}")
|
|
77
|
+
task_id = created.json().get("task_id")
|
|
78
|
+
if not task_id:
|
|
79
|
+
raise ProviderError(f"MiniMax 没有返回 task_id: {created.text[:300]}")
|
|
80
|
+
deadline = time.monotonic() + 1500
|
|
81
|
+
while time.monotonic() < deadline:
|
|
82
|
+
time.sleep(4)
|
|
83
|
+
status_res = client.get(f"{base}/v2/query/video_generation/{task_id}", headers=headers)
|
|
84
|
+
if status_res.status_code >= 400:
|
|
85
|
+
raise ProviderError(f"MiniMax 查询失败 HTTP {status_res.status_code}: {status_res.text[:300]}")
|
|
86
|
+
task = status_res.json().get("task") or {}
|
|
87
|
+
status = str(task.get("status") or "").lower()
|
|
88
|
+
if status in {"failed", "cancelled"}:
|
|
89
|
+
raise ProviderError(f"MiniMax 任务 {status}: {task.get('error') or task}")
|
|
90
|
+
if status == "succeeded":
|
|
91
|
+
url = (task.get("content") or {}).get("url")
|
|
92
|
+
if not url:
|
|
93
|
+
raise ProviderError("MiniMax 成功但没有视频 URL")
|
|
94
|
+
return self._download(client, url, output)
|
|
95
|
+
raise ProviderError("MiniMax 任务超时")
|
|
96
|
+
payload = {
|
|
97
|
+
"model": model_name,
|
|
98
|
+
"prompt": prompt,
|
|
99
|
+
"duration": 6 if int(duration) <= 6 else 10,
|
|
100
|
+
"resolution": "768P" if resolution not in {"1080P", "2K"} else "1080P",
|
|
101
|
+
}
|
|
102
|
+
if images:
|
|
103
|
+
payload["first_frame_image"] = _data_uri(images[0])
|
|
104
|
+
created = client.post(f"{base}/v1/video_generation", headers=headers, json=payload)
|
|
105
|
+
if created.status_code >= 400:
|
|
106
|
+
raise ProviderError(f"MiniMax 创建失败 HTTP {created.status_code}: {created.text[:300]}")
|
|
107
|
+
body = created.json()
|
|
108
|
+
base_err = body.get("base_resp") or {}
|
|
109
|
+
if base_err.get("status_code") not in (0, None):
|
|
110
|
+
raise ProviderError(f"MiniMax 拒绝:{_error_message(body)}")
|
|
111
|
+
task_id = body.get("task_id")
|
|
112
|
+
if not task_id:
|
|
113
|
+
raise ProviderError(f"MiniMax 没有返回 task_id: {created.text[:300]}")
|
|
114
|
+
deadline = time.monotonic() + 1500
|
|
115
|
+
file_id = None
|
|
116
|
+
while time.monotonic() < deadline:
|
|
117
|
+
time.sleep(4)
|
|
118
|
+
status_res = client.get(f"{base}/v1/query/video_generation", headers=headers, params={"task_id": task_id})
|
|
119
|
+
if status_res.status_code >= 400:
|
|
120
|
+
raise ProviderError(f"MiniMax 查询失败 HTTP {status_res.status_code}: {status_res.text[:300]}")
|
|
121
|
+
task = status_res.json()
|
|
122
|
+
status = str(task.get("status") or "")
|
|
123
|
+
if status.lower() in {"fail", "failed"}:
|
|
124
|
+
raise ProviderError(f"MiniMax 任务失败:{_error_message(task)}")
|
|
125
|
+
if status == "Success":
|
|
126
|
+
file_id = task.get("file_id")
|
|
127
|
+
break
|
|
128
|
+
if not file_id:
|
|
129
|
+
raise ProviderError("MiniMax 任务超时或没有 file_id")
|
|
130
|
+
file_res = client.get(f"{base}/v1/files/retrieve", headers=headers, params={"file_id": file_id})
|
|
131
|
+
if file_res.status_code >= 400:
|
|
132
|
+
raise ProviderError(f"MiniMax 文件查询失败 HTTP {file_res.status_code}: {file_res.text[:300]}")
|
|
133
|
+
file_data = file_res.json()
|
|
134
|
+
url = ((file_data.get("file") or {}).get("download_url"))
|
|
135
|
+
if not url:
|
|
136
|
+
raise ProviderError("MiniMax 文件没有 download_url")
|
|
137
|
+
return self._download(client, url, output)
|
|
138
|
+
except (httpx.HTTPError, ProviderError) as exc:
|
|
139
|
+
errors.append(f"{base}: {exc}")
|
|
140
|
+
if isinstance(exc, ProviderError) and ("余额" in str(exc) or "insufficient" in str(exc) or "1008" in str(exc)):
|
|
141
|
+
break
|
|
142
|
+
continue
|
|
143
|
+
raise ProviderError("MiniMax 请求失败:" + " | ".join(errors)[:800])
|
|
144
|
+
|
|
145
|
+
@staticmethod
|
|
146
|
+
def _download(client: httpx.Client, url: str, output: Path) -> Path:
|
|
147
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
148
|
+
with client.stream("GET", url, timeout=180.0) as response:
|
|
149
|
+
response.raise_for_status()
|
|
150
|
+
with output.open("wb") as handle:
|
|
151
|
+
for chunk in response.iter_bytes():
|
|
152
|
+
handle.write(chunk)
|
|
153
|
+
if not output.is_file() or output.stat().st_size == 0:
|
|
154
|
+
raise ProviderError("MiniMax 下载结果为空")
|
|
155
|
+
return output
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""MiniMax H3 Image text-to-image adapter."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import base64
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
CN_BASE = os.environ.get("MINIMAX_API_BASE", "https://api.minimaxi.com").rstrip("/")
|
|
12
|
+
GLOBAL_BASE = os.environ.get("MINIMAX_GLOBAL_BASE", "https://api.minimax.io").rstrip("/")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _api_key() -> str:
|
|
16
|
+
return os.environ.get("MINIMAX_API_KEY", "").strip()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def generate(
|
|
20
|
+
prompt: str,
|
|
21
|
+
*,
|
|
22
|
+
model: str = "MiniMax-H3-Image",
|
|
23
|
+
aspect: str = "1:1",
|
|
24
|
+
area: str = "2K",
|
|
25
|
+
output: Path,
|
|
26
|
+
) -> dict:
|
|
27
|
+
key = _api_key()
|
|
28
|
+
if not key:
|
|
29
|
+
raise RuntimeError("未配置 MINIMAX_API_KEY")
|
|
30
|
+
body = {
|
|
31
|
+
"model": model,
|
|
32
|
+
"prompt": prompt,
|
|
33
|
+
"aspect_ratio": aspect,
|
|
34
|
+
"area": area,
|
|
35
|
+
"output_format": "jpeg",
|
|
36
|
+
"response_format": "url",
|
|
37
|
+
"n": 1,
|
|
38
|
+
}
|
|
39
|
+
errors = []
|
|
40
|
+
for base in (CN_BASE, GLOBAL_BASE):
|
|
41
|
+
try:
|
|
42
|
+
with httpx.Client(timeout=httpx.Timeout(650.0, connect=15.0)) as client:
|
|
43
|
+
response = client.post(f"{base}/v1/images/generations", headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}, json=body)
|
|
44
|
+
if response.status_code >= 400:
|
|
45
|
+
message = response.text[:400]
|
|
46
|
+
try:
|
|
47
|
+
payload = response.json()
|
|
48
|
+
message = str((payload.get("error") or {}).get("message") or payload)
|
|
49
|
+
except Exception:
|
|
50
|
+
pass
|
|
51
|
+
raise RuntimeError(f"MiniMax 图片生成失败 HTTP {response.status_code}: {message}")
|
|
52
|
+
data = response.json()
|
|
53
|
+
rows = data.get("data") or []
|
|
54
|
+
if not rows:
|
|
55
|
+
raise RuntimeError("MiniMax 图片接口没有返回 data")
|
|
56
|
+
item = rows[0]
|
|
57
|
+
if item.get("error"):
|
|
58
|
+
err = item["error"]
|
|
59
|
+
raise RuntimeError(f"MiniMax 图片生成失败: {err.get('message') or err}")
|
|
60
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
61
|
+
if item.get("b64_json"):
|
|
62
|
+
output.write_bytes(base64.b64decode(item["b64_json"]))
|
|
63
|
+
elif item.get("url"):
|
|
64
|
+
with client.stream("GET", item["url"], timeout=180.0) as download:
|
|
65
|
+
download.raise_for_status()
|
|
66
|
+
with output.open("wb") as handle:
|
|
67
|
+
for chunk in download.iter_bytes():
|
|
68
|
+
handle.write(chunk)
|
|
69
|
+
else:
|
|
70
|
+
raise RuntimeError("MiniMax 图片结果既没有 url 也没有 b64_json")
|
|
71
|
+
if not output.is_file() or output.stat().st_size == 0:
|
|
72
|
+
raise RuntimeError("MiniMax 图片下载为空")
|
|
73
|
+
size = str(item.get("size") or "")
|
|
74
|
+
width = height = None
|
|
75
|
+
if "x" in size:
|
|
76
|
+
try:
|
|
77
|
+
width, height = [int(x) for x in size.lower().split("x", 1)]
|
|
78
|
+
except ValueError:
|
|
79
|
+
pass
|
|
80
|
+
return {"model": model, "path": str(output), "size": size, "width": width, "height": height}
|
|
81
|
+
except Exception as exc: # noqa: BLE001
|
|
82
|
+
errors.append(f"{base}: {exc}")
|
|
83
|
+
if "insufficient" in str(exc).lower() or "1008" in str(exc):
|
|
84
|
+
break
|
|
85
|
+
continue
|
|
86
|
+
raise RuntimeError("MiniMax 图片生成失败:" + " | ".join(errors)[:800])
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Local provider key storage for the first slice.
|
|
2
|
+
|
|
3
|
+
Keys are stored in `data/settings.json` with mode 0600 and mirrored into the
|
|
4
|
+
engine process environment. This is a local desktop convenience; the next
|
|
5
|
+
hardening step is to move the file to the OS keychain.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import stat
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from . import store
|
|
16
|
+
|
|
17
|
+
FILE = store.DATA / "settings.json"
|
|
18
|
+
MODEL_PREFS = store.DATA / "model_prefs.json"
|
|
19
|
+
ALLOWED = {
|
|
20
|
+
"ARK_API_KEY",
|
|
21
|
+
"KLING_API_KEY",
|
|
22
|
+
"MINIMAX_API_KEY",
|
|
23
|
+
"DEEPSEEK_API_KEY",
|
|
24
|
+
"FAL_KEY",
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _load() -> dict[str, str]:
|
|
29
|
+
try:
|
|
30
|
+
data = json.loads(FILE.read_text(encoding="utf-8"))
|
|
31
|
+
return {str(k): str(v) for k, v in data.items() if str(k) in ALLOWED and str(v).strip()}
|
|
32
|
+
except (OSError, json.JSONDecodeError):
|
|
33
|
+
return {}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def load_into_env() -> None:
|
|
37
|
+
for name, value in _load().items():
|
|
38
|
+
os.environ.setdefault(name, value)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _write(data: dict[str, str]) -> None:
|
|
42
|
+
store.ensure_dirs()
|
|
43
|
+
tmp = FILE.with_suffix(".json.tmp")
|
|
44
|
+
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
45
|
+
os.chmod(tmp, stat.S_IRUSR | stat.S_IWUSR)
|
|
46
|
+
os.replace(tmp, FILE)
|
|
47
|
+
try:
|
|
48
|
+
os.chmod(FILE, stat.S_IRUSR | stat.S_IWUSR)
|
|
49
|
+
except OSError:
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def set_key(name: str, value: str) -> dict[str, Any]:
|
|
54
|
+
name = str(name or "").strip()
|
|
55
|
+
if name not in ALLOWED:
|
|
56
|
+
raise ValueError(f"unsupported key: {name}")
|
|
57
|
+
value = str(value or "").strip()
|
|
58
|
+
data = _load()
|
|
59
|
+
if value:
|
|
60
|
+
data[name] = value
|
|
61
|
+
os.environ[name] = value
|
|
62
|
+
else:
|
|
63
|
+
data.pop(name, None)
|
|
64
|
+
os.environ.pop(name, None)
|
|
65
|
+
_write(data)
|
|
66
|
+
return status()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def status() -> list[dict[str, Any]]:
|
|
70
|
+
data = _load()
|
|
71
|
+
rows = []
|
|
72
|
+
for name in sorted(ALLOWED):
|
|
73
|
+
value = data.get(name) or os.environ.get(name) or ""
|
|
74
|
+
if value:
|
|
75
|
+
masked = (value[:4] + "…" + value[-4:]) if len(value) > 10 else "已配置"
|
|
76
|
+
else:
|
|
77
|
+
masked = ""
|
|
78
|
+
rows.append({"name": name, "present": bool(value), "masked": masked})
|
|
79
|
+
return rows
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def enabled_models() -> list[str] | None:
|
|
83
|
+
"""Return explicitly enabled model ids, or None before the first save."""
|
|
84
|
+
try:
|
|
85
|
+
data = json.loads(MODEL_PREFS.read_text(encoding="utf-8"))
|
|
86
|
+
rows = data.get("enabled_models") if isinstance(data, dict) else None
|
|
87
|
+
if isinstance(rows, list):
|
|
88
|
+
return [str(x) for x in rows if str(x).strip()]
|
|
89
|
+
except (OSError, json.JSONDecodeError):
|
|
90
|
+
pass
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def set_enabled_models(ids: list[str]) -> list[str]:
|
|
95
|
+
store.ensure_dirs()
|
|
96
|
+
rows = []
|
|
97
|
+
for value in ids:
|
|
98
|
+
value = str(value or "").strip()
|
|
99
|
+
if value and value not in rows:
|
|
100
|
+
rows.append(value)
|
|
101
|
+
tmp = MODEL_PREFS.with_suffix(".json.tmp")
|
|
102
|
+
tmp.write_text(json.dumps({"enabled_models": rows}, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
103
|
+
os.chmod(tmp, stat.S_IRUSR | stat.S_IWUSR)
|
|
104
|
+
os.replace(tmp, MODEL_PREFS)
|
|
105
|
+
try:
|
|
106
|
+
os.chmod(MODEL_PREFS, stat.S_IRUSR | stat.S_IWUSR)
|
|
107
|
+
except OSError:
|
|
108
|
+
pass
|
|
109
|
+
return rows
|