@chad.dev/dsh-adclip 0.0.0-stage → 0.1.1

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.
Files changed (51) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +28 -2
  4. package/client.js +2256 -0
  5. package/cordis.patch.yml +10 -0
  6. package/engine/requirements.txt +9 -0
  7. package/engine/src/adclip/__init__.py +0 -0
  8. package/engine/src/adclip/api.py +704 -0
  9. package/engine/src/adclip/catalog.py +341 -0
  10. package/engine/src/adclip/image_params.py +45 -0
  11. package/engine/src/adclip/intents.py +209 -0
  12. package/engine/src/adclip/llm.py +142 -0
  13. package/engine/src/adclip/media/__init__.py +0 -0
  14. package/engine/src/adclip/media/asr.py +79 -0
  15. package/engine/src/adclip/media/ffmpeg.py +294 -0
  16. package/engine/src/adclip/media/stitch.py +124 -0
  17. package/engine/src/adclip/media/subtitles.py +45 -0
  18. package/engine/src/adclip/media/vision.py +105 -0
  19. package/engine/src/adclip/models.py +127 -0
  20. package/engine/src/adclip/params.py +158 -0
  21. package/engine/src/adclip/personas.py +60 -0
  22. package/engine/src/adclip/pipeline/__init__.py +0 -0
  23. package/engine/src/adclip/pipeline/analyze.py +133 -0
  24. package/engine/src/adclip/pipeline/generate.py +196 -0
  25. package/engine/src/adclip/pipeline/image_runner.py +146 -0
  26. package/engine/src/adclip/pipeline/persona.py +56 -0
  27. package/engine/src/adclip/pipeline/post.py +40 -0
  28. package/engine/src/adclip/pipeline/qa.py +44 -0
  29. package/engine/src/adclip/pipeline/replace.py +191 -0
  30. package/engine/src/adclip/pipeline/runner.py +138 -0
  31. package/engine/src/adclip/pipeline/script.py +226 -0
  32. package/engine/src/adclip/pipeline/segment.py +87 -0
  33. package/engine/src/adclip/providers/__init__.py +0 -0
  34. package/engine/src/adclip/providers/ark.py +122 -0
  35. package/engine/src/adclip/providers/ark_image.py +114 -0
  36. package/engine/src/adclip/providers/base.py +30 -0
  37. package/engine/src/adclip/providers/discovery.py +56 -0
  38. package/engine/src/adclip/providers/kling.py +101 -0
  39. package/engine/src/adclip/providers/minimax.py +155 -0
  40. package/engine/src/adclip/providers/minimax_image.py +89 -0
  41. package/engine/src/adclip/settings.py +109 -0
  42. package/engine/src/adclip/store.py +378 -0
  43. package/host/dsh.js +60 -0
  44. package/host/engine.js +265 -0
  45. package/host/proxy.js +142 -0
  46. package/host/supervisor.js +251 -0
  47. package/icon.svg +6 -0
  48. package/index.js +39 -0
  49. package/locale/en.json +12 -0
  50. package/locale/zh.json +12 -0
  51. package/package.json +47 -4
@@ -0,0 +1,114 @@
1
+ """Volcengine Ark image generation (Seedream 4.x).
2
+
3
+ One POST to `/images/generations`, then the returned URL (or inline base64) is
4
+ written to the run's artifact path. The request shape follows Ark's image API:
5
+ `size` takes explicit pixel dimensions computed from the UI's area + aspect, and
6
+ `watermark` is off because the output is a product image.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ import mimetypes
12
+ import os
13
+ from pathlib import Path
14
+
15
+ import httpx
16
+
17
+ BASE_URL = os.environ.get("ARK_BASE_URL", "https://ark.cn-beijing.volces.com/api/v3").rstrip("/")
18
+ MODEL_ENV = "ARK_MODEL_SEEDREAM_4_0"
19
+ DEFAULT_MODEL = "doubao-seedream-4-0-20260415"
20
+
21
+
22
+ def _api_key() -> str:
23
+ key = os.environ.get("ARK_API_KEY", "").strip()
24
+ if key.lower().startswith("bearer "):
25
+ key = key[7:].strip()
26
+ return key
27
+
28
+
29
+ def _model_id(model: str) -> str:
30
+ return os.environ.get(MODEL_ENV, "").strip() or model or DEFAULT_MODEL
31
+
32
+
33
+ def _data_uri(path: Path) -> str:
34
+ mime = mimetypes.guess_type(path.name)[0] or "image/png"
35
+ return f"data:{mime};base64,{base64.b64encode(path.read_bytes()).decode('ascii')}"
36
+
37
+
38
+ def _error_message(response: httpx.Response) -> str:
39
+ message = response.text[:400]
40
+ try:
41
+ payload = response.json()
42
+ error = payload.get("error") if isinstance(payload, dict) else None
43
+ if isinstance(error, dict):
44
+ message = str(error.get("message") or message)
45
+ elif isinstance(payload, dict) and payload.get("message"):
46
+ message = str(payload["message"])
47
+ except Exception:
48
+ pass
49
+ return message
50
+
51
+
52
+ def generate(
53
+ prompt: str,
54
+ *,
55
+ model: str = DEFAULT_MODEL,
56
+ aspect: str = "1:1",
57
+ area: str = "2K",
58
+ output: Path,
59
+ reference: Path | None = None,
60
+ ) -> dict:
61
+ """Generate one image; returns its pixel size."""
62
+ from .. import image_params
63
+
64
+ key = _api_key()
65
+ if not key:
66
+ raise RuntimeError("未配置 ARK_API_KEY")
67
+ body: dict = {
68
+ "model": _model_id(model),
69
+ "prompt": prompt,
70
+ "size": image_params.size_for(area, aspect),
71
+ "response_format": "url",
72
+ "watermark": False,
73
+ "sequential_image_generation": "disabled",
74
+ }
75
+ if reference is not None and reference.is_file():
76
+ body["image"] = _data_uri(reference)
77
+ try:
78
+ with httpx.Client(timeout=httpx.Timeout(300.0, connect=15.0)) as client:
79
+ response = client.post(
80
+ f"{BASE_URL}/images/generations",
81
+ headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
82
+ json=body,
83
+ )
84
+ if response.status_code >= 400:
85
+ raise RuntimeError(f"Ark 图片生成失败 HTTP {response.status_code}: {_error_message(response)}")
86
+ payload = response.json()
87
+ rows = payload.get("data") or []
88
+ if not rows:
89
+ raise RuntimeError("Ark 图片接口没有返回 data")
90
+ item = rows[0]
91
+ if item.get("error"):
92
+ error = item["error"]
93
+ raise RuntimeError(f"Ark 图片生成失败:{error.get('message') if isinstance(error, dict) else error}")
94
+ output.parent.mkdir(parents=True, exist_ok=True)
95
+ if item.get("b64_json"):
96
+ output.write_bytes(base64.b64decode(item["b64_json"]))
97
+ elif item.get("url"):
98
+ download = client.get(str(item["url"]))
99
+ if download.status_code >= 400:
100
+ raise RuntimeError(f"Ark 图片下载失败 HTTP {download.status_code}")
101
+ output.write_bytes(download.content)
102
+ else:
103
+ raise RuntimeError("Ark 图片接口没有返回 url 或 b64_json")
104
+ except httpx.HTTPError as exc:
105
+ raise RuntimeError(f"Ark 图片请求失败:{exc}") from exc
106
+ result: dict = {}
107
+ try:
108
+ from PIL import Image
109
+
110
+ with Image.open(output) as image:
111
+ result["width"], result["height"] = image.size
112
+ except Exception:
113
+ result["width"] = result["height"] = None
114
+ return result
@@ -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,89 @@
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
+ reference: Path | None = None,
27
+ ) -> dict:
28
+ key = _api_key()
29
+ if not key:
30
+ raise RuntimeError("未配置 MINIMAX_API_KEY")
31
+ # H3 Image is text-to-image only; `reference` exists so the runner can call
32
+ # every adapter with one signature.
33
+ body = {
34
+ "model": model,
35
+ "prompt": prompt,
36
+ "aspect_ratio": aspect,
37
+ "area": area,
38
+ "output_format": "jpeg",
39
+ "response_format": "url",
40
+ "n": 1,
41
+ }
42
+ errors = []
43
+ for base in (CN_BASE, GLOBAL_BASE):
44
+ try:
45
+ with httpx.Client(timeout=httpx.Timeout(650.0, connect=15.0)) as client:
46
+ response = client.post(f"{base}/v1/images/generations", headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}, json=body)
47
+ if response.status_code >= 400:
48
+ message = response.text[:400]
49
+ try:
50
+ payload = response.json()
51
+ message = str((payload.get("error") or {}).get("message") or payload)
52
+ except Exception:
53
+ pass
54
+ raise RuntimeError(f"MiniMax 图片生成失败 HTTP {response.status_code}: {message}")
55
+ data = response.json()
56
+ rows = data.get("data") or []
57
+ if not rows:
58
+ raise RuntimeError("MiniMax 图片接口没有返回 data")
59
+ item = rows[0]
60
+ if item.get("error"):
61
+ err = item["error"]
62
+ raise RuntimeError(f"MiniMax 图片生成失败: {err.get('message') or err}")
63
+ output.parent.mkdir(parents=True, exist_ok=True)
64
+ if item.get("b64_json"):
65
+ output.write_bytes(base64.b64decode(item["b64_json"]))
66
+ elif item.get("url"):
67
+ with client.stream("GET", item["url"], timeout=180.0) as download:
68
+ download.raise_for_status()
69
+ with output.open("wb") as handle:
70
+ for chunk in download.iter_bytes():
71
+ handle.write(chunk)
72
+ else:
73
+ raise RuntimeError("MiniMax 图片结果既没有 url 也没有 b64_json")
74
+ if not output.is_file() or output.stat().st_size == 0:
75
+ raise RuntimeError("MiniMax 图片下载为空")
76
+ size = str(item.get("size") or "")
77
+ width = height = None
78
+ if "x" in size:
79
+ try:
80
+ width, height = [int(x) for x in size.lower().split("x", 1)]
81
+ except ValueError:
82
+ pass
83
+ return {"model": model, "path": str(output), "size": size, "width": width, "height": height}
84
+ except Exception as exc: # noqa: BLE001
85
+ errors.append(f"{base}: {exc}")
86
+ if "insufficient" in str(exc).lower() or "1008" in str(exc):
87
+ break
88
+ continue
89
+ 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