@dickpy/dsh-oil-slide 0.0.0-stage → 0.2.8
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 +21 -0
- package/README.md +90 -2
- package/bundled-assets/brand/empty-deck-cobalt.webp +0 -0
- package/bundled-assets/brand/oil-slide-mark-512.png +0 -0
- package/bundled-assets/skill/LICENSE +21 -0
- package/bundled-assets/skill/README.md +61 -0
- package/bundled-assets/skill/SKILL.md +185 -0
- package/bundled-assets/skill/references/art-directions.md +99 -0
- package/bundled-assets/skill/references/brand-and-canvas.md +72 -0
- package/bundled-assets/skill/references/design-baseline.txt +1 -0
- package/bundled-assets/skill/references/prompt-compiler.md +99 -0
- package/bundled-assets/skill/references/restore-and-pptx.md +178 -0
- package/bundled-assets/skill/references/staged-pptx.md +71 -0
- package/bundled-assets/skill/scripts/_runtime_utils.py +351 -0
- package/bundled-assets/skill/scripts/asset_sheet.py +528 -0
- package/bundled-assets/skill/scripts/brand_ref.py +776 -0
- package/bundled-assets/skill/scripts/crop_asset.py +1709 -0
- package/bundled-assets/skill/scripts/deck_shell.py +2322 -0
- package/bundled-assets/skill/scripts/export_images.py +280 -0
- package/bundled-assets/skill/scripts/extract_pptx.py +360 -0
- package/bundled-assets/skill/scripts/extract_slide_dom.js +1640 -0
- package/bundled-assets/skill/scripts/html_to_pptx.py +4042 -0
- package/bundled-assets/skill/scripts/measure_slide_layout.py +952 -0
- package/bundled-assets/skill/scripts/oiloil-connect.mjs +1493 -0
- package/bundled-assets/skill/scripts/oiloil-image.mjs +492 -0
- package/bundled-assets/skill/scripts/prepare_plate.py +412 -0
- package/bundled-assets/skill/scripts/render_gradient.py +258 -0
- package/bundled-assets/skill/scripts/slide_brand.py +111 -0
- package/bundled-assets/skill/scripts/slide_incremental.py +122 -0
- package/bundled-assets/skill/scripts/slide_workflow.py +711 -0
- package/bundled-assets/skill/scripts/verify_deck.py +3483 -0
- package/bundled-assets/skill/vendor/README.md +4 -0
- package/bundled-assets/skill/vendor/codex-ppt/LICENSE +21 -0
- package/bundled-assets/skill/vendor/codex-ppt/assemble_ppt.py +435 -0
- package/bundled-assets/skill/vendor/codex-ppt/codex_ppt_runtime.py +284 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_gen.py +972 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/__init__.py +6 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/atlascloud.py +222 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/base.py +32 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/factory.py +21 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/openai_compatible.py +238 -0
- package/bundled-assets/skill/vendor/codex-ppt/requirements.txt +5 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//345/205/232/346/224/277/347/272/242/351/243/216/346/240/274.md +98 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//345/210/233/346/204/217/346/235/202/345/277/227/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//345/244/215/345/217/244/346/211/201/345/271/263/346/217/222/347/224/273/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/346/212/200/346/234/257/350/247/243/351/207/212/351/243/216.md +86 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/347/231/275/346/235/277/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/231/345/255/246/350/257/276/344/273/266/351/243/216.md +107 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/260/346/215/256/344/273/252/350/241/250/347/233/230/351/243/216.md +73 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/205/347/210/275/344/270/223/344/270/232/351/243/216.md +87 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/251/346/232/226/346/211/213/345/267/245/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//347/224/265/345/255/220/345/242/250/346/260/264/346/235/202/345/277/227/351/243/216.md +86 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//347/247/221/347/240/224/347/255/224/350/276/251/351/243/216.md +138 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//351/272/246/350/202/257/351/224/241/351/243/216/346/240/274.md +119 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/LICENSE +21 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/SKILL.md +171 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/agents/openai.yaml +4 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/__init__.py +1 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/cli.py +25 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/__init__.py +1 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_input_normalization.py +355 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_page_artifacts.py +132 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/build_pptx_from_manifest.py +1029 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/configure_image_backend.py +52 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_run_state.py +214 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_text_hints.py +179 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/finalize_deck_run.py +96 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/formula_renderer.py +254 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/image_gen.py +206 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/main.py +795 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/make_page_contact_sheet.py +28 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/native_tables.py +140 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/paddle_text_hints.py +212 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_job_status.py +54 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_text_metrics.py +334 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/path_geometry.py +174 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/prepare_deck_run.py +209 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/process_asset_sheet.py +104 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_imagegen_result.py +118 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_dispatch.py +83 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_result.py +130 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/remove_chroma_key.py +441 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/reset_page_job.py +74 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/runtime_env.py +283 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/split_alpha_components.py +323 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/text_hints.py +309 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/validate_pptx.py +873 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/pyproject.toml +29 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/prompts/page-worker.md +47 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/cli-helper.md +282 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/manifest-schema.md +423 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/page-decision-tree.md +301 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/scripts/build-page-worker-prompt.py +134 -0
- package/cordis.patch.yml +3 -0
- package/lib/client.js +11423 -0
- package/lib/index.js +2638 -0
- package/package.json +140 -4
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import base64
|
|
5
|
+
import json
|
|
6
|
+
import mimetypes
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
11
|
+
from urllib.parse import urlparse
|
|
12
|
+
from urllib.request import Request, urlopen as default_urlopen
|
|
13
|
+
|
|
14
|
+
from .base import ImageProvider
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
UrlOpen = Callable[..., Any]
|
|
18
|
+
USER_AGENT = "codex-ppt-skill/0.1 (+https://github.com/ningzimu/codex-ppt-skill)"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AtlasCloudImageProvider(ImageProvider):
|
|
22
|
+
_FINISHED_STATUSES = {"completed", "succeeded"}
|
|
23
|
+
_FAILED_STATUSES = {"failed"}
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
*,
|
|
28
|
+
api_key: Optional[str],
|
|
29
|
+
base_url: Optional[str],
|
|
30
|
+
urlopen: UrlOpen = default_urlopen,
|
|
31
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
32
|
+
poll_interval: float = 2.0,
|
|
33
|
+
max_polls: int = 120,
|
|
34
|
+
) -> None:
|
|
35
|
+
self.api_key = api_key
|
|
36
|
+
self.model_base_url = _model_base_url(base_url)
|
|
37
|
+
self._urlopen = urlopen
|
|
38
|
+
self._sleep = sleep
|
|
39
|
+
self.poll_interval = poll_interval
|
|
40
|
+
self.max_polls = max_polls
|
|
41
|
+
|
|
42
|
+
def generate(self, payload: Dict[str, Any]) -> List[str]:
|
|
43
|
+
count = int(payload.get("n", 1))
|
|
44
|
+
outputs: List[str] = []
|
|
45
|
+
for _ in range(count):
|
|
46
|
+
outputs.extend(self._submit_and_collect(payload, operation="text-to-image"))
|
|
47
|
+
return outputs
|
|
48
|
+
|
|
49
|
+
def edit(
|
|
50
|
+
self,
|
|
51
|
+
payload: Dict[str, Any],
|
|
52
|
+
image_paths: List[Path],
|
|
53
|
+
mask_path: Optional[Path],
|
|
54
|
+
) -> List[str]:
|
|
55
|
+
if mask_path is not None:
|
|
56
|
+
raise ValueError("AtlasCloud image edit does not support --mask.")
|
|
57
|
+
|
|
58
|
+
count = int(payload.get("n", 1))
|
|
59
|
+
edit_payload = dict(payload)
|
|
60
|
+
edit_payload["images"] = [_image_to_data_url(path) for path in image_paths]
|
|
61
|
+
outputs: List[str] = []
|
|
62
|
+
for _ in range(count):
|
|
63
|
+
outputs.extend(self._submit_and_collect(edit_payload, operation="edit"))
|
|
64
|
+
return outputs
|
|
65
|
+
|
|
66
|
+
async def generate_batch(
|
|
67
|
+
self,
|
|
68
|
+
payload: Dict[str, Any],
|
|
69
|
+
*,
|
|
70
|
+
attempts: int,
|
|
71
|
+
job_label: str,
|
|
72
|
+
) -> List[str]:
|
|
73
|
+
last_exc: Optional[Exception] = None
|
|
74
|
+
for attempt in range(1, attempts + 1):
|
|
75
|
+
try:
|
|
76
|
+
return await asyncio.to_thread(self.generate, payload)
|
|
77
|
+
except Exception as exc:
|
|
78
|
+
last_exc = exc
|
|
79
|
+
if attempt == attempts:
|
|
80
|
+
raise
|
|
81
|
+
sleep_s = min(60.0, 2.0**attempt)
|
|
82
|
+
print(
|
|
83
|
+
f"{job_label} attempt {attempt}/{attempts} failed ({exc.__class__.__name__}); retrying in {sleep_s:.1f}s",
|
|
84
|
+
file=sys.stderr,
|
|
85
|
+
)
|
|
86
|
+
await asyncio.sleep(sleep_s)
|
|
87
|
+
raise last_exc or RuntimeError("unknown error")
|
|
88
|
+
|
|
89
|
+
def _submit_and_collect(self, payload: Dict[str, Any], *, operation: str) -> List[str]:
|
|
90
|
+
request_payload = self._atlas_payload(payload, operation=operation)
|
|
91
|
+
submitted = self._request_json(
|
|
92
|
+
"POST",
|
|
93
|
+
f"{self.model_base_url}/generateImage",
|
|
94
|
+
request_payload,
|
|
95
|
+
)
|
|
96
|
+
prediction_id = _prediction_id(submitted)
|
|
97
|
+
if not prediction_id:
|
|
98
|
+
raise RuntimeError("AtlasCloud response did not include a prediction id.")
|
|
99
|
+
|
|
100
|
+
result_url = _prediction_result_url(submitted) or f"{self.model_base_url}/result/{prediction_id}"
|
|
101
|
+
result = self._poll_prediction(result_url)
|
|
102
|
+
outputs = result.get("outputs")
|
|
103
|
+
if not isinstance(outputs, list) or not outputs:
|
|
104
|
+
raise RuntimeError("AtlasCloud prediction completed without outputs.")
|
|
105
|
+
return [self._output_to_b64(str(output)) for output in outputs]
|
|
106
|
+
|
|
107
|
+
def _poll_prediction(self, url: str) -> Dict[str, Any]:
|
|
108
|
+
last: Dict[str, Any] = {}
|
|
109
|
+
for _ in range(self.max_polls):
|
|
110
|
+
last = self._request_json("GET", url)
|
|
111
|
+
status = str(last.get("status", "")).lower()
|
|
112
|
+
if status in self._FINISHED_STATUSES:
|
|
113
|
+
return last
|
|
114
|
+
if status in self._FAILED_STATUSES:
|
|
115
|
+
raise RuntimeError(f"AtlasCloud prediction failed: {last}")
|
|
116
|
+
self._sleep(self.poll_interval)
|
|
117
|
+
raise TimeoutError(f"AtlasCloud prediction timed out: {last}")
|
|
118
|
+
|
|
119
|
+
def _atlas_payload(self, payload: Dict[str, Any], *, operation: str) -> Dict[str, Any]:
|
|
120
|
+
output_format = payload.get("output_format")
|
|
121
|
+
if output_format not in (None, "png", "jpeg"):
|
|
122
|
+
raise ValueError("AtlasCloud supports output_format png or jpeg.")
|
|
123
|
+
|
|
124
|
+
body: Dict[str, Any] = {
|
|
125
|
+
"model": atlascloud_model_for_operation(
|
|
126
|
+
str(payload.get("model", "gpt-image-2")),
|
|
127
|
+
operation,
|
|
128
|
+
),
|
|
129
|
+
"prompt": payload["prompt"],
|
|
130
|
+
"enable_sync_mode": False,
|
|
131
|
+
"enable_base64_output": True,
|
|
132
|
+
}
|
|
133
|
+
for key in ("size", "quality", "output_format"):
|
|
134
|
+
value = payload.get(key)
|
|
135
|
+
if value is not None and value != "auto":
|
|
136
|
+
body[key] = value
|
|
137
|
+
if operation == "edit":
|
|
138
|
+
body["images"] = payload["images"]
|
|
139
|
+
return body
|
|
140
|
+
|
|
141
|
+
def _request_json(
|
|
142
|
+
self,
|
|
143
|
+
method: str,
|
|
144
|
+
url: str,
|
|
145
|
+
payload: Optional[Dict[str, Any]] = None,
|
|
146
|
+
) -> Dict[str, Any]:
|
|
147
|
+
data = json.dumps(payload).encode("utf-8") if payload is not None else None
|
|
148
|
+
headers = {
|
|
149
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
150
|
+
"Accept": "application/json",
|
|
151
|
+
"User-Agent": USER_AGENT,
|
|
152
|
+
}
|
|
153
|
+
if payload is not None:
|
|
154
|
+
headers["Content-Type"] = "application/json"
|
|
155
|
+
request = Request(url, data=data, headers=headers, method=method)
|
|
156
|
+
with self._urlopen(request, timeout=60) as response:
|
|
157
|
+
parsed = json.loads(response.read().decode("utf-8"))
|
|
158
|
+
if not isinstance(parsed, dict):
|
|
159
|
+
raise RuntimeError(f"Unexpected AtlasCloud response: {parsed}")
|
|
160
|
+
code = parsed.get("code")
|
|
161
|
+
if code is not None and code not in (0, 200, "0", "200"):
|
|
162
|
+
raise RuntimeError(f"AtlasCloud API error: {parsed}")
|
|
163
|
+
data_obj = parsed.get("data", parsed)
|
|
164
|
+
if not isinstance(data_obj, dict):
|
|
165
|
+
raise RuntimeError(f"Unexpected AtlasCloud response data: {parsed}")
|
|
166
|
+
return data_obj
|
|
167
|
+
|
|
168
|
+
def _output_to_b64(self, value: str) -> str:
|
|
169
|
+
if value.startswith("data:") and "," in value:
|
|
170
|
+
return value.split(",", 1)[1]
|
|
171
|
+
parsed = urlparse(value)
|
|
172
|
+
if parsed.scheme in {"http", "https"}:
|
|
173
|
+
request = Request(value, headers={"User-Agent": USER_AGENT}, method="GET")
|
|
174
|
+
with self._urlopen(request, timeout=60) as response:
|
|
175
|
+
return base64.b64encode(response.read()).decode("ascii")
|
|
176
|
+
return value
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _model_base_url(base_url: Optional[str]) -> str:
|
|
180
|
+
if not base_url:
|
|
181
|
+
return "https://api.atlascloud.ai/api/v1/model"
|
|
182
|
+
parsed = urlparse(base_url)
|
|
183
|
+
origin = f"{parsed.scheme}://{parsed.netloc}" if parsed.scheme and parsed.netloc else ""
|
|
184
|
+
path = parsed.path.rstrip("/")
|
|
185
|
+
marker = "/api/v1/model"
|
|
186
|
+
if marker in path:
|
|
187
|
+
prefix = path[: path.index(marker) + len(marker)]
|
|
188
|
+
return f"{origin}{prefix}"
|
|
189
|
+
if origin:
|
|
190
|
+
return f"{origin}{marker}"
|
|
191
|
+
return base_url.rstrip("/")
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def atlascloud_model_for_operation(model: str, operation: str) -> str:
|
|
195
|
+
suffix = "edit" if operation == "edit" else "text-to-image"
|
|
196
|
+
base = model.rstrip("/")
|
|
197
|
+
for existing_suffix in ("/text-to-image", "/edit"):
|
|
198
|
+
if base.endswith(existing_suffix):
|
|
199
|
+
base = base[: -len(existing_suffix)]
|
|
200
|
+
break
|
|
201
|
+
if "/" not in base:
|
|
202
|
+
base = f"openai/{base}"
|
|
203
|
+
return f"{base}/{suffix}"
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _prediction_id(data: Dict[str, Any]) -> Optional[str]:
|
|
207
|
+
value = data.get("id") or data.get("prediction_id")
|
|
208
|
+
return str(value) if value else None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _prediction_result_url(data: Dict[str, Any]) -> Optional[str]:
|
|
212
|
+
urls = data.get("urls")
|
|
213
|
+
if not isinstance(urls, dict):
|
|
214
|
+
return None
|
|
215
|
+
value = urls.get("get")
|
|
216
|
+
return str(value) if value else None
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _image_to_data_url(path: Path) -> str:
|
|
220
|
+
mime = mimetypes.guess_type(str(path))[0] or "application/octet-stream"
|
|
221
|
+
encoded = base64.b64encode(path.read_bytes()).decode("ascii")
|
|
222
|
+
return f"data:{mime};base64,{encoded}"
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Dict, List, Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ImageProvider(ABC):
|
|
9
|
+
"""Common API shape used by image_gen.py command handlers."""
|
|
10
|
+
|
|
11
|
+
@abstractmethod
|
|
12
|
+
def generate(self, payload: Dict[str, Any]) -> List[str]:
|
|
13
|
+
"""Generate images and return base64-encoded image payloads."""
|
|
14
|
+
|
|
15
|
+
@abstractmethod
|
|
16
|
+
def edit(
|
|
17
|
+
self,
|
|
18
|
+
payload: Dict[str, Any],
|
|
19
|
+
image_paths: List[Path],
|
|
20
|
+
mask_path: Optional[Path],
|
|
21
|
+
) -> List[str]:
|
|
22
|
+
"""Edit input images and return base64-encoded image payloads."""
|
|
23
|
+
|
|
24
|
+
@abstractmethod
|
|
25
|
+
async def generate_batch(
|
|
26
|
+
self,
|
|
27
|
+
payload: Dict[str, Any],
|
|
28
|
+
*,
|
|
29
|
+
attempts: int,
|
|
30
|
+
job_label: str,
|
|
31
|
+
) -> List[str]:
|
|
32
|
+
"""Generate one batch job with provider-specific retry behavior."""
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
from urllib.parse import urlparse
|
|
5
|
+
|
|
6
|
+
from .atlascloud import AtlasCloudImageProvider
|
|
7
|
+
from .base import ImageProvider
|
|
8
|
+
from .openai_compatible import OpenAICompatibleImageProvider
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def create_image_provider(*, api_key: Optional[str], base_url: Optional[str]) -> ImageProvider:
|
|
12
|
+
if _is_atlascloud_base_url(base_url):
|
|
13
|
+
return AtlasCloudImageProvider(api_key=api_key, base_url=base_url)
|
|
14
|
+
return OpenAICompatibleImageProvider(api_key=api_key, base_url=base_url)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _is_atlascloud_base_url(base_url: Optional[str]) -> bool:
|
|
18
|
+
if not base_url:
|
|
19
|
+
return False
|
|
20
|
+
hostname = urlparse(base_url).hostname or ""
|
|
21
|
+
return "atlascloud.ai" in hostname.lower()
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
9
|
+
|
|
10
|
+
from .base import ImageProvider
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
ClientFactory = Callable[[], Any]
|
|
14
|
+
DEFAULT_RUNTIME_HOME = "~/.codex-ppt-skill"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _runtime_home() -> Path:
|
|
18
|
+
return Path(os.getenv("CODEX_PPT_HOME", DEFAULT_RUNTIME_HOME)).expanduser()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _runtime_python_path() -> str:
|
|
22
|
+
home = _runtime_home()
|
|
23
|
+
if os.name == "nt":
|
|
24
|
+
return str(home / ".venv" / "Scripts" / "python.exe")
|
|
25
|
+
return str(home / ".venv" / "bin" / "python")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _skill_root() -> Path:
|
|
29
|
+
return Path(__file__).resolve().parents[1]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _dependency_hint(package: str, *, upgrade: bool = False) -> str:
|
|
33
|
+
package_arg = f"-U {package}" if upgrade else package
|
|
34
|
+
runtime_python = _runtime_python_path()
|
|
35
|
+
requirements = _skill_root() / "requirements.txt"
|
|
36
|
+
return (
|
|
37
|
+
"Install codex-ppt dependencies in the shared runtime first, for example "
|
|
38
|
+
f"`python3 {_skill_root() / 'codex_ppt_runtime.py'} bootstrap`, "
|
|
39
|
+
f"or install {package} directly with `{runtime_python} -m pip install "
|
|
40
|
+
f"{package_arg}`. Requirements file: `{requirements}`."
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _extract_retry_after_seconds(exc: Exception) -> Optional[float]:
|
|
45
|
+
for attr in ("retry_after", "retry_after_seconds"):
|
|
46
|
+
val = getattr(exc, attr, None)
|
|
47
|
+
if isinstance(val, (int, float)) and val >= 0:
|
|
48
|
+
return float(val)
|
|
49
|
+
msg = str(exc)
|
|
50
|
+
m = re.search(r"retry[- ]after[:= ]+([0-9]+(?:\\.[0-9]+)?)", msg, re.IGNORECASE)
|
|
51
|
+
if m:
|
|
52
|
+
try:
|
|
53
|
+
return float(m.group(1))
|
|
54
|
+
except Exception:
|
|
55
|
+
return None
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _is_rate_limit_error(exc: Exception) -> bool:
|
|
60
|
+
name = exc.__class__.__name__.lower()
|
|
61
|
+
if "ratelimit" in name or "rate_limit" in name:
|
|
62
|
+
return True
|
|
63
|
+
msg = str(exc).lower()
|
|
64
|
+
return "429" in msg or "rate limit" in msg or "too many requests" in msg
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _is_transient_error(exc: Exception) -> bool:
|
|
68
|
+
if _is_rate_limit_error(exc):
|
|
69
|
+
return True
|
|
70
|
+
name = exc.__class__.__name__.lower()
|
|
71
|
+
if "timeout" in name or "timedout" in name or "tempor" in name:
|
|
72
|
+
return True
|
|
73
|
+
msg = str(exc).lower()
|
|
74
|
+
return "timeout" in msg or "timed out" in msg or "connection reset" in msg
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
async def _generate_one_with_retries(
|
|
78
|
+
client: Any,
|
|
79
|
+
payload: Dict[str, Any],
|
|
80
|
+
*,
|
|
81
|
+
attempts: int,
|
|
82
|
+
job_label: str,
|
|
83
|
+
) -> Any:
|
|
84
|
+
last_exc: Optional[Exception] = None
|
|
85
|
+
for attempt in range(1, attempts + 1):
|
|
86
|
+
try:
|
|
87
|
+
return await client.images.generate(**payload)
|
|
88
|
+
except Exception as exc:
|
|
89
|
+
last_exc = exc
|
|
90
|
+
if not _is_transient_error(exc):
|
|
91
|
+
raise
|
|
92
|
+
if attempt == attempts:
|
|
93
|
+
raise
|
|
94
|
+
sleep_s = _extract_retry_after_seconds(exc)
|
|
95
|
+
if sleep_s is None:
|
|
96
|
+
sleep_s = min(60.0, 2.0**attempt)
|
|
97
|
+
print(
|
|
98
|
+
f"{job_label} attempt {attempt}/{attempts} failed ({exc.__class__.__name__}); retrying in {sleep_s:.1f}s",
|
|
99
|
+
file=sys.stderr,
|
|
100
|
+
)
|
|
101
|
+
await asyncio.sleep(sleep_s)
|
|
102
|
+
raise last_exc or RuntimeError("unknown error")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class OpenAICompatibleImageProvider(ImageProvider):
|
|
106
|
+
def __init__(
|
|
107
|
+
self,
|
|
108
|
+
*,
|
|
109
|
+
api_key: Optional[str],
|
|
110
|
+
base_url: Optional[str],
|
|
111
|
+
client_factory: Optional[ClientFactory] = None,
|
|
112
|
+
async_client_factory: Optional[ClientFactory] = None,
|
|
113
|
+
) -> None:
|
|
114
|
+
self.api_key = api_key
|
|
115
|
+
self.base_url = base_url
|
|
116
|
+
self._client_factory = client_factory
|
|
117
|
+
self._async_client_factory = async_client_factory
|
|
118
|
+
self._async_client: Optional[Any] = None
|
|
119
|
+
|
|
120
|
+
def generate(self, payload: Dict[str, Any]) -> List[str]:
|
|
121
|
+
result = self._create_client().images.generate(**payload)
|
|
122
|
+
return [item.b64_json for item in result.data]
|
|
123
|
+
|
|
124
|
+
def edit(
|
|
125
|
+
self,
|
|
126
|
+
payload: Dict[str, Any],
|
|
127
|
+
image_paths: List[Path],
|
|
128
|
+
mask_path: Optional[Path],
|
|
129
|
+
) -> List[str]:
|
|
130
|
+
with _open_files(image_paths) as image_files, _open_mask(mask_path) as mask_file:
|
|
131
|
+
request = dict(payload)
|
|
132
|
+
request["image"] = image_files if len(image_files) > 1 else image_files[0]
|
|
133
|
+
if mask_file is not None:
|
|
134
|
+
request["mask"] = mask_file
|
|
135
|
+
result = self._create_client().images.edit(**request)
|
|
136
|
+
return [item.b64_json for item in result.data]
|
|
137
|
+
|
|
138
|
+
async def generate_batch(
|
|
139
|
+
self,
|
|
140
|
+
payload: Dict[str, Any],
|
|
141
|
+
*,
|
|
142
|
+
attempts: int,
|
|
143
|
+
job_label: str,
|
|
144
|
+
) -> List[str]:
|
|
145
|
+
result = await _generate_one_with_retries(
|
|
146
|
+
self._create_async_client(),
|
|
147
|
+
payload,
|
|
148
|
+
attempts=attempts,
|
|
149
|
+
job_label=job_label,
|
|
150
|
+
)
|
|
151
|
+
return [item.b64_json for item in result.data]
|
|
152
|
+
|
|
153
|
+
def _create_client(self) -> Any:
|
|
154
|
+
if self._client_factory is not None:
|
|
155
|
+
return self._client_factory()
|
|
156
|
+
try:
|
|
157
|
+
from openai import OpenAI
|
|
158
|
+
except ImportError as exc:
|
|
159
|
+
raise RuntimeError(
|
|
160
|
+
f"openai SDK not installed in the active environment. {_dependency_hint('openai')}"
|
|
161
|
+
) from exc
|
|
162
|
+
return OpenAI(api_key=self.api_key, base_url=self.base_url)
|
|
163
|
+
|
|
164
|
+
def _create_async_client(self) -> Any:
|
|
165
|
+
if self._async_client is not None:
|
|
166
|
+
return self._async_client
|
|
167
|
+
if self._async_client_factory is not None:
|
|
168
|
+
self._async_client = self._async_client_factory()
|
|
169
|
+
return self._async_client
|
|
170
|
+
try:
|
|
171
|
+
from openai import AsyncOpenAI
|
|
172
|
+
except ImportError as exc:
|
|
173
|
+
try:
|
|
174
|
+
import openai as _openai # noqa: F401
|
|
175
|
+
except ImportError:
|
|
176
|
+
raise RuntimeError(
|
|
177
|
+
f"openai SDK not installed in the active environment. {_dependency_hint('openai')}"
|
|
178
|
+
) from exc
|
|
179
|
+
raise RuntimeError(
|
|
180
|
+
"AsyncOpenAI not available in this openai SDK version. "
|
|
181
|
+
f"{_dependency_hint('openai', upgrade=True)}"
|
|
182
|
+
) from exc
|
|
183
|
+
self._async_client = AsyncOpenAI(api_key=self.api_key, base_url=self.base_url)
|
|
184
|
+
return self._async_client
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _open_files(paths: List[Path]):
|
|
188
|
+
return _FileBundle(paths)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _open_mask(mask_path: Optional[Path]):
|
|
192
|
+
if mask_path is None:
|
|
193
|
+
return _NullContext()
|
|
194
|
+
return _SingleFile(mask_path)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class _NullContext:
|
|
198
|
+
def __enter__(self):
|
|
199
|
+
return None
|
|
200
|
+
|
|
201
|
+
def __exit__(self, exc_type, exc, tb):
|
|
202
|
+
return False
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class _SingleFile:
|
|
206
|
+
def __init__(self, path: Path):
|
|
207
|
+
self._path = path
|
|
208
|
+
self._handle = None
|
|
209
|
+
|
|
210
|
+
def __enter__(self):
|
|
211
|
+
self._handle = self._path.open("rb")
|
|
212
|
+
return self._handle
|
|
213
|
+
|
|
214
|
+
def __exit__(self, exc_type, exc, tb):
|
|
215
|
+
if self._handle:
|
|
216
|
+
try:
|
|
217
|
+
self._handle.close()
|
|
218
|
+
except Exception:
|
|
219
|
+
pass
|
|
220
|
+
return False
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class _FileBundle:
|
|
224
|
+
def __init__(self, paths: List[Path]):
|
|
225
|
+
self._paths = paths
|
|
226
|
+
self._handles: List[object] = []
|
|
227
|
+
|
|
228
|
+
def __enter__(self):
|
|
229
|
+
self._handles = [p.open("rb") for p in self._paths]
|
|
230
|
+
return self._handles
|
|
231
|
+
|
|
232
|
+
def __exit__(self, exc_type, exc, tb):
|
|
233
|
+
for handle in self._handles:
|
|
234
|
+
try:
|
|
235
|
+
handle.close()
|
|
236
|
+
except Exception:
|
|
237
|
+
pass
|
|
238
|
+
return False
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# 党政红风格
|
|
2
|
+
|
|
3
|
+
**适用场景:**
|
|
4
|
+
- 党政机关工作汇报、专题学习与会议材料
|
|
5
|
+
- 政策宣讲、党建活动、年度总结与重点工作部署
|
|
6
|
+
- 国企、事业单位和公共服务机构的正式汇报
|
|
7
|
+
|
|
8
|
+
**GPT-Image-2 风格 Brief:**
|
|
9
|
+
```json
|
|
10
|
+
{
|
|
11
|
+
"type": "16:9 full-slide PowerPoint image",
|
|
12
|
+
"style_name": "党政红风格",
|
|
13
|
+
"best_for": "党政机关、国企和事业单位的工作汇报、政策宣讲、党建学习、年度总结与重点工作部署",
|
|
14
|
+
"visual_direction": "solemn, authoritative, and optimistic Chinese public-sector presentation with a recognizable Chinese-red identity, restrained gold accents, strong Chinese typography, and a visual expression shaped by the subject rather than a fixed ceremonial layout",
|
|
15
|
+
"canvas": {
|
|
16
|
+
"aspect_ratio": "16:9",
|
|
17
|
+
"background": "choose red, warm ivory, a restrained gradient, a relevant photograph, or a subtle abstract treatment according to the page role and subject; any landscape, architecture, ribbon, skyline, or cultural motif is optional and must serve the content rather than become a default background",
|
|
18
|
+
"composition": "formal and balanced with a prominent title hierarchy and disciplined alignment; allow centered, asymmetric, image-led, modular, or spacious compositions when they better express the content",
|
|
19
|
+
"density": "medium information density with controlled whitespace, clear reading order, and enough supporting text or evidence to make each page useful"
|
|
20
|
+
},
|
|
21
|
+
"color_palette": {
|
|
22
|
+
"primary": "Chinese red #C41E3A for main titles, structural emphasis, and key labels",
|
|
23
|
+
"secondary": "deep red #9E1530 for contrast and warm ivory #FFF9F2 for the main canvas",
|
|
24
|
+
"accent": "restrained matte gold #D6A84B and warm amber #E9A11B for icons, connectors, and small title ornaments",
|
|
25
|
+
"neutral": "ink black #262626, dark gray #4A4A4A, pale warm gray #F3EEE7",
|
|
26
|
+
"rule": "use Chinese red to establish authority and gold as a restrained accent. Balance red, warm ivory, and neutral space according to page role; avoid glitter, glossy gradients, and festive red-and-gold decoration"
|
|
27
|
+
},
|
|
28
|
+
"typography": {
|
|
29
|
+
"title": "large bold Microsoft YaHei or Source Han Sans style Chinese sans-serif, visually strong, dignified, and immediately noticeable",
|
|
30
|
+
"body": "Microsoft YaHei or Source Han Sans style Chinese sans-serif, concise, highly readable, and aligned to a strict grid",
|
|
31
|
+
"labels": "bold white or dark-red text on restrained red or pale-gold blocks",
|
|
32
|
+
"text_quality": "all Chinese text must be exact, fully legible, non-garbled, and suitable for formal government reporting"
|
|
33
|
+
},
|
|
34
|
+
"title_system": {
|
|
35
|
+
"consistency_rule": "Keep the title hierarchy, typeface, weight, color logic, and spacing consistent across slides of the same page type.",
|
|
36
|
+
"cover": "Use a prominent, dignified title treatment that may be centered, offset, or integrated with a relevant visual according to the composition.",
|
|
37
|
+
"section_divider": "Use a concise title and a clear transition in scale, color, whitespace, or imagery without requiring a fixed navigation bar or ornament.",
|
|
38
|
+
"content_slide": "Keep the page topic immediately recognizable, but align the title with the composition and information structure; centered and left-aligned treatments are both valid.",
|
|
39
|
+
"flexibility": "Treat the title system as a hierarchy and consistency rule, not a fixed arrangement. Do not require a navigation strip, centered title, gold separator, numbering style, or identical decoration on every slide."
|
|
40
|
+
},
|
|
41
|
+
"layout_patterns": [
|
|
42
|
+
"cover or opener with a dominant title and a subject-relevant photographic, illustrative, architectural, landscape, or abstract visual",
|
|
43
|
+
"section divider with a concise statement and a clear transition created through scale, whitespace, color, or imagery",
|
|
44
|
+
"content explanation organized around the most important relationship, argument, process, comparison, or evidence",
|
|
45
|
+
"work deployment or policy interpretation page whose modules, sequence, and emphasis follow the source content",
|
|
46
|
+
"achievement or data page combining key figures, charts, images, and evidence-based captions as needed",
|
|
47
|
+
"summary or closing page that reinforces the central message with a strong but restrained visual conclusion"
|
|
48
|
+
],
|
|
49
|
+
"layout_usage_rule": "Keep the red-led identity, typography, and formal tone consistent while varying title placement, background treatment, imagery, information structure, and whitespace by page purpose. Do not force every slide into the same grid, module count, title position, or decorative motif; use lighter backgrounds when they improve readability.",
|
|
50
|
+
"layout_blueprints": [
|
|
51
|
+
{
|
|
52
|
+
"name": "封面 / 开场",
|
|
53
|
+
"sections": [
|
|
54
|
+
{"position": "primary visual field", "count": 1, "labels": ["prominent title and concise supporting information"]},
|
|
55
|
+
{"position": "supporting field", "count": 1, "labels": ["optional subject-relevant photograph, illustration, architecture, landscape, or abstract visual"]}
|
|
56
|
+
]
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
"name": "信息阐释 / 工作部署",
|
|
60
|
+
"sections": [
|
|
61
|
+
{"position": "title zone", "count": 1, "labels": ["clear page topic or guiding statement"]},
|
|
62
|
+
{"position": "main content field", "count": 1, "labels": ["the dominant argument, relationship, process, comparison, or evidence structure"]},
|
|
63
|
+
{"position": "supporting field", "count": 1, "labels": ["supporting text, data, images, or callouts selected according to the source"]}
|
|
64
|
+
]
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
"name": "成果 / 总结",
|
|
68
|
+
"sections": [
|
|
69
|
+
{"position": "primary message field", "count": 1, "labels": ["central conclusion, achievement, or call to action"]},
|
|
70
|
+
{"position": "evidence field", "count": 1, "labels": ["figures, chart, comparison, documentary image, or concise supporting points as appropriate"]}
|
|
71
|
+
]
|
|
72
|
+
}
|
|
73
|
+
],
|
|
74
|
+
"visual_elements": {
|
|
75
|
+
"allowed": "content-relevant photography, illustrations, landscapes, architecture, skylines, public-service scenes, people, abstract ribbons or color fields, restrained red-and-gold accents, formal information modules, simple icons, clean charts, and subtle cultural motifs; none of these elements is mandatory",
|
|
76
|
+
"avoid": "repeating the same landmark or ornament without content justification, invented or inaccurate official marks, excessive ceremonial decoration, thick shadows, glossy 3D text, glitter, festival or wedding motifs, cartoon styling, unrelated stock imagery, and decorative elements that compete with the message"
|
|
77
|
+
},
|
|
78
|
+
"image_treatment": {
|
|
79
|
+
"photos": "use relevant and credible documentary, landscape, architectural, public-service, or institutional imagery; it may be full-bleed, cropped, framed, or integrated with a restrained red treatment, but avoid heavy filters that obscure the subject",
|
|
80
|
+
"screenshots": "place inside clean warm-white frames with short source labels and no ornamental clutter",
|
|
81
|
+
"charts": "use red as the primary series, gold for one key highlight, and neutral gray for comparison; keep labels direct and readable",
|
|
82
|
+
"illustrations": "choose a flat, graphic, painterly, or restrained symbolic treatment according to the subject; do not impose a fixed landmark, ribbon, skyline, or landscape motif",
|
|
83
|
+
"official_symbols": "use a party emblem, national emblem, flag, seal, or other official symbol only when the content genuinely requires it and an accurate, authorized source asset is available; never invent, approximate, or redesign official symbols"
|
|
84
|
+
},
|
|
85
|
+
"rendering_constraints": [
|
|
86
|
+
"The slide must look like a formal Chinese government or public-sector report, not a festival poster or commercial advertisement.",
|
|
87
|
+
"Use large, dignified Chinese sans-serif typography resembling Microsoft YaHei or Source Han Sans.",
|
|
88
|
+
"Follow a consistent title system across slides of the same page type, while allowing cover, section-divider, and content-slide variants.",
|
|
89
|
+
"Let the page role and source content determine title placement, background, imagery, module count, and composition.",
|
|
90
|
+
"Do not force a navigation strip, centered title, gold separator, landscape, Great Wall, skyline, ribbon, or other specific motif onto every slide.",
|
|
91
|
+
"Use Chinese red #C41E3A as the main red and gold as a restrained supporting accent.",
|
|
92
|
+
"Keep gold restrained and matte; do not use glossy metallic or embossed 3D text.",
|
|
93
|
+
"Use exact readable Chinese text and a clear top-to-bottom or left-to-right hierarchy.",
|
|
94
|
+
"Do not invent, approximate, or redesign official marks, government logos, party emblems, national emblems, seals, flags, or institutional names.",
|
|
95
|
+
"No watermark and no unrelated logo."
|
|
96
|
+
]
|
|
97
|
+
}
|
|
98
|
+
```
|