@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.
Files changed (97) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +90 -2
  3. package/bundled-assets/brand/empty-deck-cobalt.webp +0 -0
  4. package/bundled-assets/brand/oil-slide-mark-512.png +0 -0
  5. package/bundled-assets/skill/LICENSE +21 -0
  6. package/bundled-assets/skill/README.md +61 -0
  7. package/bundled-assets/skill/SKILL.md +185 -0
  8. package/bundled-assets/skill/references/art-directions.md +99 -0
  9. package/bundled-assets/skill/references/brand-and-canvas.md +72 -0
  10. package/bundled-assets/skill/references/design-baseline.txt +1 -0
  11. package/bundled-assets/skill/references/prompt-compiler.md +99 -0
  12. package/bundled-assets/skill/references/restore-and-pptx.md +178 -0
  13. package/bundled-assets/skill/references/staged-pptx.md +71 -0
  14. package/bundled-assets/skill/scripts/_runtime_utils.py +351 -0
  15. package/bundled-assets/skill/scripts/asset_sheet.py +528 -0
  16. package/bundled-assets/skill/scripts/brand_ref.py +776 -0
  17. package/bundled-assets/skill/scripts/crop_asset.py +1709 -0
  18. package/bundled-assets/skill/scripts/deck_shell.py +2322 -0
  19. package/bundled-assets/skill/scripts/export_images.py +280 -0
  20. package/bundled-assets/skill/scripts/extract_pptx.py +360 -0
  21. package/bundled-assets/skill/scripts/extract_slide_dom.js +1640 -0
  22. package/bundled-assets/skill/scripts/html_to_pptx.py +4042 -0
  23. package/bundled-assets/skill/scripts/measure_slide_layout.py +952 -0
  24. package/bundled-assets/skill/scripts/oiloil-connect.mjs +1493 -0
  25. package/bundled-assets/skill/scripts/oiloil-image.mjs +492 -0
  26. package/bundled-assets/skill/scripts/prepare_plate.py +412 -0
  27. package/bundled-assets/skill/scripts/render_gradient.py +258 -0
  28. package/bundled-assets/skill/scripts/slide_brand.py +111 -0
  29. package/bundled-assets/skill/scripts/slide_incremental.py +122 -0
  30. package/bundled-assets/skill/scripts/slide_workflow.py +711 -0
  31. package/bundled-assets/skill/scripts/verify_deck.py +3483 -0
  32. package/bundled-assets/skill/vendor/README.md +4 -0
  33. package/bundled-assets/skill/vendor/codex-ppt/LICENSE +21 -0
  34. package/bundled-assets/skill/vendor/codex-ppt/assemble_ppt.py +435 -0
  35. package/bundled-assets/skill/vendor/codex-ppt/codex_ppt_runtime.py +284 -0
  36. package/bundled-assets/skill/vendor/codex-ppt/image_gen.py +972 -0
  37. package/bundled-assets/skill/vendor/codex-ppt/image_providers/__init__.py +6 -0
  38. package/bundled-assets/skill/vendor/codex-ppt/image_providers/atlascloud.py +222 -0
  39. package/bundled-assets/skill/vendor/codex-ppt/image_providers/base.py +32 -0
  40. package/bundled-assets/skill/vendor/codex-ppt/image_providers/factory.py +21 -0
  41. package/bundled-assets/skill/vendor/codex-ppt/image_providers/openai_compatible.py +238 -0
  42. package/bundled-assets/skill/vendor/codex-ppt/requirements.txt +5 -0
  43. 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
  44. 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
  45. 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
  46. 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
  47. 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
  48. 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
  49. 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
  50. 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
  51. 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
  52. 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
  53. 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
  54. 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
  55. package/bundled-assets/skill/vendor/image-to-editable-ppt/LICENSE +21 -0
  56. package/bundled-assets/skill/vendor/image-to-editable-ppt/SKILL.md +171 -0
  57. package/bundled-assets/skill/vendor/image-to-editable-ppt/agents/openai.yaml +4 -0
  58. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/__init__.py +1 -0
  59. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/cli.py +25 -0
  60. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/__init__.py +1 -0
  61. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_input_normalization.py +355 -0
  62. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_page_artifacts.py +132 -0
  63. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/build_pptx_from_manifest.py +1029 -0
  64. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/configure_image_backend.py +52 -0
  65. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_run_state.py +214 -0
  66. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_text_hints.py +179 -0
  67. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/finalize_deck_run.py +96 -0
  68. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/formula_renderer.py +254 -0
  69. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/image_gen.py +206 -0
  70. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/main.py +795 -0
  71. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/make_page_contact_sheet.py +28 -0
  72. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/native_tables.py +140 -0
  73. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/paddle_text_hints.py +212 -0
  74. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_job_status.py +54 -0
  75. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_text_metrics.py +334 -0
  76. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/path_geometry.py +174 -0
  77. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/prepare_deck_run.py +209 -0
  78. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/process_asset_sheet.py +104 -0
  79. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_imagegen_result.py +118 -0
  80. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_dispatch.py +83 -0
  81. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_result.py +130 -0
  82. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/remove_chroma_key.py +441 -0
  83. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/reset_page_job.py +74 -0
  84. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/runtime_env.py +283 -0
  85. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/split_alpha_components.py +323 -0
  86. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/text_hints.py +309 -0
  87. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/validate_pptx.py +873 -0
  88. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/pyproject.toml +29 -0
  89. package/bundled-assets/skill/vendor/image-to-editable-ppt/prompts/page-worker.md +47 -0
  90. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/cli-helper.md +282 -0
  91. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/manifest-schema.md +423 -0
  92. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/page-decision-tree.md +301 -0
  93. package/bundled-assets/skill/vendor/image-to-editable-ppt/scripts/build-page-worker-prompt.py +134 -0
  94. package/cordis.patch.yml +3 -0
  95. package/lib/client.js +11423 -0
  96. package/lib/index.js +2638 -0
  97. package/package.json +140 -4
@@ -0,0 +1,254 @@
1
+ #!/usr/bin/env python3
2
+ """Render LaTeX formulas into image assets for page manifests."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import shutil
8
+ import subprocess
9
+ import tempfile
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+
14
+ DEFAULT_ENGINE_CANDIDATES = ("xelatex", "lualatex", "pdflatex")
15
+ DEFAULT_TIMEOUT = 120
16
+ DEFAULT_DPI = 300
17
+ SUPPORTED_FORMATS = {"svg", "png", "pdf"}
18
+
19
+
20
+ class FormulaRenderError(RuntimeError):
21
+ pass
22
+
23
+
24
+ def select_latex_engine(engine: str | None = None) -> str:
25
+ if engine and engine != "auto":
26
+ resolved = shutil.which(engine)
27
+ if not resolved:
28
+ raise FormulaRenderError(f"LaTeX engine not found: {engine}")
29
+ return resolved
30
+ for candidate in DEFAULT_ENGINE_CANDIDATES:
31
+ resolved = shutil.which(candidate)
32
+ if resolved:
33
+ return resolved
34
+ raise FormulaRenderError(
35
+ "No LaTeX engine found. Install a TeX distribution that provides xelatex, lualatex, or pdflatex."
36
+ )
37
+
38
+
39
+ def render_latex_asset(
40
+ *,
41
+ tex: str,
42
+ out: str | Path,
43
+ page_dir: str | Path | None = None,
44
+ output_format: str | None = None,
45
+ engine: str | None = None,
46
+ preamble: str = "",
47
+ full_document: bool = False,
48
+ display: bool = True,
49
+ dpi: int = DEFAULT_DPI,
50
+ timeout: int = DEFAULT_TIMEOUT,
51
+ shell_escape: bool = False,
52
+ keep_workdir: str | Path | None = None,
53
+ ) -> dict[str, Any]:
54
+ if not tex.strip():
55
+ raise FormulaRenderError("LaTeX input is empty.")
56
+ out_path = resolve_output_path(out, page_dir)
57
+ fmt = normalise_format(output_format, out_path)
58
+ source_tex = out_path.with_suffix(".tex")
59
+ source_tex.parent.mkdir(parents=True, exist_ok=True)
60
+ document = build_latex_document(tex, preamble=preamble, full_document=full_document, display=display)
61
+ source_tex.write_text(document, encoding="utf-8")
62
+
63
+ resolved_engine = select_latex_engine(engine)
64
+ with tempfile.TemporaryDirectory() as tmp:
65
+ workdir = Path(tmp)
66
+ work_tex = workdir / "formula.tex"
67
+ work_tex.write_text(document, encoding="utf-8")
68
+ command = [
69
+ resolved_engine,
70
+ "-interaction=nonstopmode",
71
+ "-halt-on-error",
72
+ "-file-line-error",
73
+ ]
74
+ if shell_escape:
75
+ command.append("-shell-escape")
76
+ command.append(work_tex.name)
77
+ result = subprocess.run(
78
+ command,
79
+ cwd=workdir,
80
+ text=True,
81
+ capture_output=True,
82
+ timeout=timeout,
83
+ )
84
+ if result.returncode != 0:
85
+ _maybe_keep_workdir(workdir, keep_workdir)
86
+ raise FormulaRenderError(_latex_error_message(result))
87
+ pdf = workdir / "formula.pdf"
88
+ if not pdf.exists():
89
+ _maybe_keep_workdir(workdir, keep_workdir)
90
+ raise FormulaRenderError("LaTeX completed but formula.pdf was not produced.")
91
+ converter = convert_pdf(pdf, out_path, fmt, dpi=dpi, timeout=timeout)
92
+ _maybe_keep_workdir(workdir, keep_workdir)
93
+ return {
94
+ "out": str(out_path),
95
+ "format": fmt,
96
+ "tex_source": str(source_tex),
97
+ "engine": Path(resolved_engine).name,
98
+ "converter": converter,
99
+ }
100
+
101
+
102
+ def build_latex_document(tex: str, *, preamble: str = "", full_document: bool = False, display: bool = True) -> str:
103
+ if full_document:
104
+ return tex if tex.endswith("\n") else tex + "\n"
105
+ body = tex.strip()
106
+ if display:
107
+ body = "\\[\n" + body + "\n\\]"
108
+ else:
109
+ body = "$" + body + "$"
110
+ return (
111
+ "\\documentclass[border=2pt]{standalone}\n"
112
+ "\\usepackage{amsmath,amssymb,mathtools,bm}\n"
113
+ "\\usepackage{xcolor}\n"
114
+ f"{preamble.strip()}\n"
115
+ "\\begin{document}\n"
116
+ f"{body}\n"
117
+ "\\end{document}\n"
118
+ )
119
+
120
+
121
+ def convert_pdf(pdf: Path, out_path: Path, fmt: str, *, dpi: int, timeout: int) -> str:
122
+ out_path.parent.mkdir(parents=True, exist_ok=True)
123
+ if fmt == "pdf":
124
+ shutil.copy2(pdf, out_path)
125
+ return "copy-pdf"
126
+ if fmt == "svg":
127
+ dvisvgm = shutil.which("dvisvgm")
128
+ if dvisvgm:
129
+ command = [dvisvgm, "--pdf", "--no-fonts", "--exact", "--output", str(out_path), str(pdf)]
130
+ _run_converter(command, timeout)
131
+ return "dvisvgm"
132
+ pdf2svg = shutil.which("pdf2svg")
133
+ if pdf2svg:
134
+ command = [pdf2svg, str(pdf), str(out_path)]
135
+ _run_converter(command, timeout)
136
+ return "pdf2svg"
137
+ raise FormulaRenderError("SVG output requires dvisvgm or pdf2svg.")
138
+ if fmt == "png":
139
+ magick = shutil.which("magick") or shutil.which("convert")
140
+ if not magick:
141
+ raise FormulaRenderError("PNG output requires ImageMagick (`magick` or `convert`).")
142
+ command = [magick, "-density", str(dpi), str(pdf), "-trim", "+repage", str(out_path)]
143
+ _run_converter(command, timeout)
144
+ return Path(magick).name
145
+ raise FormulaRenderError(f"Unsupported formula output format: {fmt}")
146
+
147
+
148
+ def formula_image_fragment(
149
+ *,
150
+ formula_id: str,
151
+ image_path: str | Path,
152
+ tex_source: str | Path,
153
+ box_px: str | list[Any],
154
+ page_dir: str | Path | None = None,
155
+ z_index: int = 220,
156
+ alt: str | None = None,
157
+ ) -> dict[str, Any]:
158
+ path_for_manifest = manifest_path(image_path, page_dir)
159
+ tex_for_manifest = manifest_path(tex_source, page_dir)
160
+ return {
161
+ "schema_version": 1,
162
+ "type": "latex-formula-image-fragment",
163
+ "images": [
164
+ {
165
+ "id": formula_id,
166
+ "path": path_for_manifest,
167
+ "box_px": parse_box_px(box_px),
168
+ "alt": alt or f"LaTeX rendered formula {formula_id}",
169
+ "z_index": z_index,
170
+ }
171
+ ],
172
+ "asset_provenance": [
173
+ {
174
+ "path": path_for_manifest,
175
+ "source": tex_for_manifest,
176
+ "source_type": "latex-rendered-formula",
177
+ "provenance_note": "Rendered from LaTeX by editppt formula render-latex; visual fidelity is prioritized over formula editability.",
178
+ }
179
+ ],
180
+ "formula_inventory": [
181
+ {
182
+ "id": formula_id,
183
+ "decision": "latex-rendered-image",
184
+ "editable": False,
185
+ "image": path_for_manifest,
186
+ "tex_source": tex_for_manifest,
187
+ }
188
+ ],
189
+ }
190
+
191
+
192
+ def write_json(payload: dict[str, Any], path: str | Path) -> None:
193
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
194
+ Path(path).write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
195
+
196
+
197
+ def resolve_output_path(out: str | Path, page_dir: str | Path | None = None) -> Path:
198
+ path = Path(out)
199
+ if not path.is_absolute() and page_dir:
200
+ path = Path(page_dir) / path
201
+ return path.resolve()
202
+
203
+
204
+ def normalise_format(output_format: str | None, out_path: Path) -> str:
205
+ fmt = (output_format or out_path.suffix.lstrip(".") or "svg").lower()
206
+ if fmt == "jpg":
207
+ fmt = "jpeg"
208
+ if fmt not in SUPPORTED_FORMATS:
209
+ raise FormulaRenderError(f"Unsupported formula output format: {fmt}. Use svg, png, or pdf.")
210
+ return fmt
211
+
212
+
213
+ def parse_box_px(value: str | list[Any]) -> list[float]:
214
+ parts = [part.strip() for part in value.split(",")] if isinstance(value, str) else list(value)
215
+ if len(parts) != 4:
216
+ raise FormulaRenderError("box_px must be x,y,width,height")
217
+ return [float(part) for part in parts]
218
+
219
+
220
+ def manifest_path(path: str | Path, page_dir: str | Path | None = None) -> str:
221
+ resolved = Path(path).resolve()
222
+ if page_dir:
223
+ root = Path(page_dir).resolve()
224
+ try:
225
+ return resolved.relative_to(root).as_posix()
226
+ except ValueError:
227
+ pass
228
+ return resolved.as_posix()
229
+
230
+
231
+ def _run_converter(command: list[str], timeout: int) -> None:
232
+ result = subprocess.run(command, text=True, capture_output=True, timeout=timeout)
233
+ if result.returncode != 0:
234
+ raise FormulaRenderError(
235
+ "Formula conversion failed: "
236
+ + " ".join(command)
237
+ + "\n"
238
+ + "\n".join((result.stderr or result.stdout or "").splitlines()[-20:])
239
+ )
240
+
241
+
242
+ def _latex_error_message(result: subprocess.CompletedProcess[str]) -> str:
243
+ log = result.stdout or result.stderr or ""
244
+ tail = "\n".join(log.splitlines()[-30:])
245
+ return f"LaTeX render failed with exit code {result.returncode}.\n{tail}"
246
+
247
+
248
+ def _maybe_keep_workdir(workdir: Path, keep_workdir: str | Path | None) -> None:
249
+ if not keep_workdir:
250
+ return
251
+ target = Path(keep_workdir)
252
+ if target.exists():
253
+ shutil.rmtree(target)
254
+ shutil.copytree(workdir, target)
@@ -0,0 +1,206 @@
1
+ #!/usr/bin/env python3
2
+ """Generate and edit images through the user's explicitly configured Images API."""
3
+ import argparse
4
+ import base64
5
+ from contextlib import ExitStack
6
+ from io import BytesIO
7
+ import json
8
+ import mimetypes
9
+ import os
10
+ from pathlib import Path
11
+ import sys
12
+ import tempfile
13
+ from urllib.parse import urlsplit
14
+
15
+
16
+ def checked_channel(url, model, key):
17
+ if not isinstance(url, str) or not isinstance(model, str) or not url.strip() or not model.strip():
18
+ raise ValueError("请先在 Oil Slide → 生图设置选择默认模型,或设置 OPENAI_BASE_URL 和 CODEX_PPT_IMAGE_MODEL。")
19
+ if not isinstance(key, str) or any(char in key for char in "\r\n"):
20
+ raise ValueError("Invalid image provider key configuration.")
21
+ parts = urlsplit(url.strip())
22
+ if parts.scheme not in ("http", "https") or not parts.hostname or parts.username or parts.password or parts.query or parts.fragment:
23
+ raise ValueError("Base URL must be an HTTP(S) API root without embedded credentials, query or fragment.")
24
+ return url.strip().rstrip("/"), model.strip(), key.strip()
25
+
26
+
27
+ def read_channels(model_override=None):
28
+ home = Path.home()
29
+ if os.name == "nt":
30
+ root = Path(os.environ.get("APPDATA", "").strip() or home / "AppData/Roaming")
31
+ else:
32
+ root = Path(os.environ.get("XDG_CONFIG_HOME", "").strip() or home / ".config")
33
+ path = root / "oil-slide/image-channel.json"
34
+ if path.exists():
35
+ config = json.loads(path.read_text(encoding="utf-8"))
36
+ if not isinstance(config, dict):
37
+ raise ValueError("Invalid image-channel.json")
38
+ if config.get("version") == 2:
39
+ by_id = {channel["id"]: channel for channel in config["channels"]}
40
+ order = []
41
+ for ref in config["routes"]:
42
+ channel = by_id[ref["channelId"]]
43
+ if ref["model"] not in channel["models"]:
44
+ raise ValueError("The image order references an unconfigured model.")
45
+ route = checked_channel(channel["baseUrl"], ref["model"], channel.get("apiKey", ""))
46
+ if route not in order:
47
+ order.append(route)
48
+ if not order:
49
+ raise ValueError("请先在 Oil Slide → 生图设置选择默认模型。")
50
+ else:
51
+ order = [checked_channel(config.get("baseUrl"), config.get("model"), config.get("apiKey", ""))]
52
+ if model_override and model_override != order[0][1]:
53
+ raise ValueError("Model differs from the saved default. Update it in 生图设置.")
54
+ return order
55
+
56
+ url = os.getenv("OPENAI_BASE_URL", "")
57
+ model = model_override or os.getenv("CODEX_PPT_IMAGE_MODEL") or os.getenv("IMAGE_TO_EDITABLE_PPT_IMAGE_MODEL", "")
58
+ key = os.getenv("OPENAI_API_KEY", "")
59
+ if not url:
60
+ from runtime_env import config_path, read_config_file
61
+ if config_path().is_file():
62
+ legacy = read_config_file(config_path())
63
+ url = legacy.get("OPENAI_BASE_URL", "")
64
+ model = model_override or legacy.get("IMAGE_TO_EDITABLE_PPT_IMAGE_MODEL", "")
65
+ key = legacy.get("OPENAI_API_KEY", "")
66
+ return [checked_channel(url, model, key)]
67
+
68
+
69
+ def read_channel(model_override=None):
70
+ return read_channels(model_override)[0]
71
+
72
+
73
+ class ProviderUnavailable(Exception):
74
+ """Another configured model may be able to handle this request."""
75
+
76
+
77
+ def post_image(url, endpoint, model, key, data, args):
78
+ import requests
79
+ attachments = []
80
+ if args.image:
81
+ field = "image[]" if len(args.image) > 1 else "image"
82
+ attachments.extend((field, image) for image in args.image)
83
+ if args.mask:
84
+ attachments.append(("mask", args.mask))
85
+
86
+ # Reopen inputs per attempt so a backup gets the same reference bytes and mask.
87
+ with ExitStack() as stack:
88
+ files = []
89
+ for field, image in attachments:
90
+ mime = mimetypes.guess_type(image.name)[0] or "application/octet-stream"
91
+ files.append((field, (image.name, stack.enter_context(image.open("rb")), mime)))
92
+ body = {"data": dict(data, model=model), "files": files} if files else {"json": dict(data, model=model)}
93
+ headers = {"Authorization": "Bearer " + key} if key else {}
94
+ try:
95
+ response = requests.post(url + endpoint, headers=headers, timeout=args.timeout, allow_redirects=False, **body)
96
+ except (requests.ConnectionError, requests.Timeout) as exc:
97
+ raise ProviderUnavailable(type(exc).__name__) from None
98
+
99
+ if 200 <= response.status_code < 300:
100
+ return response
101
+ try:
102
+ error = response.json().get("error", {})
103
+ code = error.get("code") if isinstance(error, dict) else None
104
+ except (ValueError, AttributeError):
105
+ code = None
106
+ status = response.status_code
107
+ if code in ("content_policy_violation", "moderation_blocked", "safety_violation"):
108
+ raise ValueError(f"生图请求被渠道内容策略拒绝(HTTP {status})。")
109
+ if status in (401, 402, 403, 404, 405, 408, 410, 429, 502, 503, 504, 500) or code in (
110
+ "model_not_found", "model_not_available", "model_not_supported", "unsupported_model",
111
+ "deployment_not_found", "insufficient_quota", "rate_limit_exceeded",
112
+ ):
113
+ raise ProviderUnavailable(f"HTTP {status}")
114
+ raise ValueError(f"生图渠道返回 HTTP {status},请检查请求参数和 Images API 支持情况。")
115
+
116
+
117
+ def request_image(routes, endpoint, data, args):
118
+ for index, (url, model, key) in enumerate(routes):
119
+ try:
120
+ return post_image(url, endpoint, model, key, data, args)
121
+ except ProviderUnavailable as exc:
122
+ if index == len(routes) - 1:
123
+ detail = "所有已配置的生图模型均不可用" if index else "生图渠道不可用"
124
+ raise ValueError(f"{detail}({exc})。请检查渠道状态与模型配置。") from None
125
+ next_model = routes[index + 1][1]
126
+ print(f"生图模型 {model} 不可用({exc}),切换到备用模型 {next_model}。", file=sys.stderr)
127
+
128
+
129
+
130
+ def main(argv=None):
131
+ p = argparse.ArgumentParser(description=__doc__)
132
+ p.add_argument("command", choices=["generate", "edit"])
133
+ prompt = p.add_mutually_exclusive_group(required=True)
134
+ prompt.add_argument("--prompt")
135
+ prompt.add_argument("--prompt-file", type=Path)
136
+ p.add_argument("--model", help="Model alias for environment-only configuration")
137
+ p.add_argument("--size", default="auto")
138
+ p.add_argument("--quality", default="auto")
139
+ p.add_argument("--image", action="append", type=Path, default=[])
140
+ p.add_argument("--mask", type=Path)
141
+ p.add_argument("--background")
142
+ p.add_argument("--timeout", type=float, default=600)
143
+ p.add_argument("--out", type=Path, default=Path("output/imagegen/output.png"))
144
+ p.add_argument("--force", action="store_true")
145
+ p.add_argument("--dry-run", action="store_true")
146
+ a = p.parse_args(argv)
147
+ try:
148
+ routes = read_channels(a.model)
149
+ endpoint = "/images/edits" if a.command == "edit" else "/images/generations"
150
+ if (a.command == "edit") != bool(a.image) or (a.mask and not a.image):
151
+ raise ValueError("Use edit with --image for every reference; masks require an edit.")
152
+ text = a.prompt_file.read_text(encoding="utf-8") if a.prompt_file else a.prompt
153
+ if not text.strip() or a.timeout <= 0:
154
+ raise ValueError("A prompt and a positive timeout are required.")
155
+ data = dict(prompt=text, size=a.size, quality=a.quality)
156
+ if a.background:
157
+ data["background"] = a.background
158
+ if a.dry_run:
159
+ url, model, _ = routes[0]
160
+ print(json.dumps({"endpoint": url + endpoint, "model": model, "references": len(a.image),
161
+ "backup_models": [route[1] for route in routes[1:]]}))
162
+ return 0
163
+ formats = {".jpg": "JPEG", ".jpeg": "JPEG", ".png": "PNG", ".webp": "WEBP"}
164
+ fmt = formats.get(a.out.suffix.lower())
165
+ if not fmt or (a.out.exists() and not a.force):
166
+ raise ValueError("Use a new PNG, JPEG or WebP output path, or pass --force.")
167
+ import requests
168
+ from PIL import Image
169
+ resp = request_image(routes, endpoint, data, a)
170
+ item = resp.json()["data"][0]
171
+ if item.get("b64_json"):
172
+ raw = base64.b64decode(item["b64_json"], validate=True)
173
+ elif item.get("url") and urlsplit(item["url"]).scheme in ("http", "https"):
174
+ # Provider-hosted result URLs may point to a CDN. Never forward the channel key.
175
+ result = requests.get(item["url"], timeout=a.timeout)
176
+ if result.status_code != 200:
177
+ raise ValueError(f"下载渠道返回的图片失败(HTTP {result.status_code})")
178
+ raw = result.content
179
+ else:
180
+ raise ValueError("The channel returned neither b64_json nor an image URL.")
181
+ a.out.parent.mkdir(parents=True, exist_ok=True)
182
+ with tempfile.TemporaryDirectory(dir=a.out.parent) as temp:
183
+ fresh = Path(temp) / "image"
184
+ with Image.open(BytesIO(raw)) as image:
185
+ image.load()
186
+ if image.format == fmt:
187
+ fresh.write_bytes(raw)
188
+ else:
189
+ if fmt == "JPEG":
190
+ image = image.convert("RGB")
191
+ image.save(fresh, format=fmt)
192
+ if a.force:
193
+ fresh.replace(a.out)
194
+ else:
195
+ os.link(fresh, a.out)
196
+ print(a.out)
197
+ return 0
198
+ except (OSError, ValueError, KeyError, IndexError, TypeError, ImportError) as exc:
199
+ # Requests exceptions may include signed URLs. Print only their category.
200
+ message = type(exc).__name__ if type(exc).__module__.startswith("requests") else str(exc)
201
+ print(f"Image channel: {message}", file=sys.stderr)
202
+ return 1
203
+
204
+
205
+ if __name__ == "__main__":
206
+ raise SystemExit(main())