@dickpy/dsh-oil-slide 0.0.0-stage → 0.2.7
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 +89 -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 +11282 -0
- package/lib/index.js +2638 -0
- package/package.json +140 -4
|
@@ -0,0 +1,972 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Fallback CLI for codex-ppt image generation or editing with GPT Image models.
|
|
3
|
+
|
|
4
|
+
Used when Codex's built-in image tool is unavailable, when the user explicitly
|
|
5
|
+
opts into API mode, or needs output controls exposed by the API.
|
|
6
|
+
|
|
7
|
+
Defaults to gpt-image-2.5-flare and a structured prompt augmentation workflow.
|
|
8
|
+
Reads OPENAI_API_KEY, and optionally OPENAI_BASE_URL for provider adapters or
|
|
9
|
+
OpenAI-compatible proxy providers.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import asyncio
|
|
16
|
+
import base64
|
|
17
|
+
from io import BytesIO
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
import re
|
|
22
|
+
import sys
|
|
23
|
+
import time
|
|
24
|
+
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
|
25
|
+
from urllib.parse import urlparse
|
|
26
|
+
|
|
27
|
+
from image_providers import create_image_provider
|
|
28
|
+
from image_providers.atlascloud import atlascloud_model_for_operation
|
|
29
|
+
|
|
30
|
+
DEFAULT_MODEL = "gpt-image-2.5-flare"
|
|
31
|
+
DEFAULT_SIZE = "2560x1440"
|
|
32
|
+
DEFAULT_QUALITY = "medium"
|
|
33
|
+
DEFAULT_OUTPUT_FORMAT = "png"
|
|
34
|
+
DEFAULT_CONCURRENCY = 5
|
|
35
|
+
DEFAULT_DOWNSCALE_SUFFIX = "-web"
|
|
36
|
+
DEFAULT_OUTPUT_PATH = "output/imagegen/output.png"
|
|
37
|
+
GPT_IMAGE_MODEL_PREFIX = "gpt-image-"
|
|
38
|
+
|
|
39
|
+
ALLOWED_LEGACY_SIZES = {"1024x1024", "1536x1024", "1024x1536", "auto"}
|
|
40
|
+
ALLOWED_QUALITIES = {"low", "medium", "high", "xhigh", "max", "auto"}
|
|
41
|
+
ALLOWED_BACKGROUNDS = {"transparent", "opaque", "auto", None}
|
|
42
|
+
ALLOWED_INPUT_FIDELITIES = {"low", "high", None}
|
|
43
|
+
|
|
44
|
+
GPT_IMAGE_2_MIN_PIXELS = 655_360
|
|
45
|
+
GPT_IMAGE_2_MAX_PIXELS = 8_294_400
|
|
46
|
+
GPT_IMAGE_2_MAX_EDGE = 3840
|
|
47
|
+
GPT_IMAGE_2_MAX_RATIO = 3.0
|
|
48
|
+
|
|
49
|
+
MAX_IMAGE_BYTES = 50 * 1024 * 1024
|
|
50
|
+
MAX_BATCH_JOBS = 500
|
|
51
|
+
DEFAULT_RUNTIME_HOME = "~/.codex-ppt-skill"
|
|
52
|
+
ENV_FIELDS = ("OPENAI_API_KEY", "OPENAI_BASE_URL", "CODEX_PPT_IMAGE_MODEL")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _die(message: str, code: int = 1) -> None:
|
|
56
|
+
print(f"Error: {message}", file=sys.stderr)
|
|
57
|
+
raise SystemExit(code)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _warn(message: str) -> None:
|
|
61
|
+
print(f"Warning: {message}", file=sys.stderr)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _runtime_home() -> Path:
|
|
65
|
+
return Path(os.getenv("CODEX_PPT_HOME", DEFAULT_RUNTIME_HOME)).expanduser()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _runtime_env_path() -> Path:
|
|
69
|
+
return _runtime_home() / ".env"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _load_runtime_env() -> None:
|
|
73
|
+
path = _runtime_env_path()
|
|
74
|
+
if not path.exists():
|
|
75
|
+
return
|
|
76
|
+
for raw in path.read_text(encoding="utf-8").splitlines():
|
|
77
|
+
line = raw.strip()
|
|
78
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
79
|
+
continue
|
|
80
|
+
key, value = line.split("=", 1)
|
|
81
|
+
key = key.strip()
|
|
82
|
+
if key not in ENV_FIELDS or os.getenv(key):
|
|
83
|
+
continue
|
|
84
|
+
value = value.strip().strip('"').strip("'")
|
|
85
|
+
os.environ[key] = value
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _default_model() -> str:
|
|
89
|
+
return os.getenv("CODEX_PPT_IMAGE_MODEL", DEFAULT_MODEL)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _api_base_url() -> Optional[str]:
|
|
93
|
+
return os.getenv("OPENAI_BASE_URL") or None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _api_target_label() -> str:
|
|
97
|
+
base_url = _api_base_url()
|
|
98
|
+
if base_url:
|
|
99
|
+
if _is_atlascloud_base_url(base_url):
|
|
100
|
+
return f"AtlasCloud provider adapter (OPENAI_BASE_URL={base_url})"
|
|
101
|
+
return f"third-party image API or OpenAI-compatible proxy (OPENAI_BASE_URL={base_url})"
|
|
102
|
+
return "official OpenAI API (OPENAI_BASE_URL unset)"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _is_atlascloud_base_url(base_url: str) -> bool:
|
|
106
|
+
hostname = urlparse(base_url).hostname or ""
|
|
107
|
+
return "atlascloud.ai" in hostname.lower()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _preview_endpoint(kind: str) -> str:
|
|
111
|
+
base_url = _api_base_url()
|
|
112
|
+
if base_url and _is_atlascloud_base_url(base_url):
|
|
113
|
+
return "/api/v1/model/generateImage"
|
|
114
|
+
if kind == "edit":
|
|
115
|
+
return "/v1/images/edits"
|
|
116
|
+
return "/v1/images/generations"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _preview_model(model: str, kind: str) -> str:
|
|
120
|
+
base_url = _api_base_url()
|
|
121
|
+
if base_url and _is_atlascloud_base_url(base_url):
|
|
122
|
+
operation = "edit" if kind == "edit" else "text-to-image"
|
|
123
|
+
return atlascloud_model_for_operation(model, operation)
|
|
124
|
+
return model
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _runtime_python_path() -> str:
|
|
128
|
+
home = _runtime_home()
|
|
129
|
+
if os.name == "nt":
|
|
130
|
+
return str(home / ".venv" / "Scripts" / "python.exe")
|
|
131
|
+
return str(home / ".venv" / "bin" / "python")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _skill_root() -> Path:
|
|
135
|
+
return Path(__file__).resolve().parents[1]
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _dependency_hint(package: str, *, upgrade: bool = False) -> str:
|
|
139
|
+
package_arg = f"-U {package}" if upgrade else package
|
|
140
|
+
runtime_python = _runtime_python_path()
|
|
141
|
+
requirements = _skill_root() / "requirements.txt"
|
|
142
|
+
return (
|
|
143
|
+
"Install codex-ppt dependencies in the shared runtime first, for example "
|
|
144
|
+
f"`python3 {_skill_root() / 'scripts' / 'codex_ppt_runtime.py'} bootstrap`, "
|
|
145
|
+
f"or install {package} directly with `{runtime_python} -m pip install "
|
|
146
|
+
f"{package_arg}`. Requirements file: `{requirements}`."
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _ensure_api_key(dry_run: bool) -> None:
|
|
151
|
+
if os.getenv("OPENAI_API_KEY"):
|
|
152
|
+
print(f"OPENAI_API_KEY is set. API target: {_api_target_label()}.", file=sys.stderr)
|
|
153
|
+
return
|
|
154
|
+
if dry_run:
|
|
155
|
+
_warn(f"OPENAI_API_KEY is not set; dry-run only. API target: {_api_target_label()}.")
|
|
156
|
+
return
|
|
157
|
+
runtime_script = _skill_root() / "scripts" / "codex_ppt_runtime.py"
|
|
158
|
+
config_doc = _skill_root() / "docs" / "image-model-configuration.md"
|
|
159
|
+
base_url = _api_base_url()
|
|
160
|
+
model = _default_model()
|
|
161
|
+
if base_url:
|
|
162
|
+
command = (
|
|
163
|
+
f'python3 {runtime_script} config --api-key "your-api-key" '
|
|
164
|
+
f'--base-url "{base_url}" --model {model}'
|
|
165
|
+
)
|
|
166
|
+
target_hint = f"Detected third-party OpenAI-compatible API via OPENAI_BASE_URL={base_url}."
|
|
167
|
+
else:
|
|
168
|
+
command = f'python3 {runtime_script} config --api-key "your-api-key" --model {model}'
|
|
169
|
+
target_hint = "Detected official OpenAI API mode because OPENAI_BASE_URL is not set."
|
|
170
|
+
_die(
|
|
171
|
+
"OPENAI_API_KEY is not set for codex-ppt CLI/API fallback.\n"
|
|
172
|
+
f"{target_hint}\n"
|
|
173
|
+
"Use the built-in image tool if it is available. Otherwise configure the shared runtime once:\n"
|
|
174
|
+
f" {command}\n"
|
|
175
|
+
"To use a third-party proxy, set OPENAI_BASE_URL and the provider's model name.\n"
|
|
176
|
+
f"Details: {config_doc}"
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _read_prompt(prompt: Optional[str], prompt_file: Optional[str]) -> str:
|
|
181
|
+
if prompt and prompt_file:
|
|
182
|
+
_die("Use --prompt or --prompt-file, not both.")
|
|
183
|
+
if prompt_file:
|
|
184
|
+
if prompt_file == "-":
|
|
185
|
+
return sys.stdin.read().strip()
|
|
186
|
+
path = Path(prompt_file)
|
|
187
|
+
if not path.exists():
|
|
188
|
+
_die(f"Prompt file not found: {path}")
|
|
189
|
+
return path.read_text(encoding="utf-8").strip()
|
|
190
|
+
if prompt:
|
|
191
|
+
return prompt.strip()
|
|
192
|
+
_die("Missing prompt. Use --prompt or --prompt-file.")
|
|
193
|
+
return "" # unreachable
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _check_image_paths(paths: Iterable[str]) -> List[Path]:
|
|
197
|
+
resolved: List[Path] = []
|
|
198
|
+
for raw in paths:
|
|
199
|
+
path = Path(raw)
|
|
200
|
+
if not path.exists():
|
|
201
|
+
_die(f"Image file not found: {path}")
|
|
202
|
+
if path.stat().st_size > MAX_IMAGE_BYTES:
|
|
203
|
+
_warn(f"Image exceeds 50MB limit: {path}")
|
|
204
|
+
resolved.append(path)
|
|
205
|
+
return resolved
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _normalize_output_format(fmt: Optional[str]) -> str:
|
|
209
|
+
if not fmt:
|
|
210
|
+
return DEFAULT_OUTPUT_FORMAT
|
|
211
|
+
fmt = fmt.lower()
|
|
212
|
+
if fmt not in {"png", "jpeg", "jpg", "webp"}:
|
|
213
|
+
_die("output-format must be png, jpeg, jpg, or webp.")
|
|
214
|
+
return "jpeg" if fmt == "jpg" else fmt
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _parse_size(size: str) -> Optional[Tuple[int, int]]:
|
|
218
|
+
match = re.fullmatch(r"([1-9][0-9]*)x([1-9][0-9]*)", size)
|
|
219
|
+
if not match:
|
|
220
|
+
return None
|
|
221
|
+
return int(match.group(1)), int(match.group(2))
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _validate_gpt_image_2_size(size: str) -> None:
|
|
225
|
+
if size == "auto":
|
|
226
|
+
return
|
|
227
|
+
|
|
228
|
+
parsed = _parse_size(size)
|
|
229
|
+
if parsed is None:
|
|
230
|
+
_die("size must be auto or WIDTHxHEIGHT, for example 1024x1024.")
|
|
231
|
+
|
|
232
|
+
width, height = parsed
|
|
233
|
+
max_edge = max(width, height)
|
|
234
|
+
min_edge = min(width, height)
|
|
235
|
+
total_pixels = width * height
|
|
236
|
+
|
|
237
|
+
if max_edge > GPT_IMAGE_2_MAX_EDGE:
|
|
238
|
+
_die("GPT Image 2 / 2.5 / 2.6 size maximum edge length must be less than or equal to 3840px.")
|
|
239
|
+
if width % 16 != 0 or height % 16 != 0:
|
|
240
|
+
_die("GPT Image 2 / 2.5 / 2.6 size width and height must be multiples of 16px.")
|
|
241
|
+
if max_edge / min_edge > GPT_IMAGE_2_MAX_RATIO:
|
|
242
|
+
_die("GPT Image 2 / 2.5 / 2.6 size long edge to short edge ratio must not exceed 3:1.")
|
|
243
|
+
if total_pixels < GPT_IMAGE_2_MIN_PIXELS or total_pixels > GPT_IMAGE_2_MAX_PIXELS:
|
|
244
|
+
_die(
|
|
245
|
+
"GPT Image 2 / 2.5 / 2.6 size total pixels must be at least 655,360 and no more than 8,294,400."
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _validate_size(size: str, model: str) -> None:
|
|
250
|
+
if _is_gpt_image_2_model(model) or _is_gpt_image_2_5_or_2_6_model(model):
|
|
251
|
+
_validate_gpt_image_2_size(size)
|
|
252
|
+
return
|
|
253
|
+
|
|
254
|
+
if size not in ALLOWED_LEGACY_SIZES:
|
|
255
|
+
_die(
|
|
256
|
+
"size must be one of 1024x1024, 1536x1024, 1024x1536, or auto for this GPT Image model."
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _validate_quality(quality: str, model: str) -> None:
|
|
261
|
+
if quality not in ALLOWED_QUALITIES:
|
|
262
|
+
_die("quality must be one of low, medium, high, xhigh, max, or auto.")
|
|
263
|
+
if quality in {"xhigh", "max"} and not _is_gpt_image_2_5_or_2_6_model(model):
|
|
264
|
+
_die("xhigh and max quality require GPT Image 2.5 or 2.6 (Flare or Sunburst).")
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _validate_background(background: Optional[str]) -> None:
|
|
268
|
+
if background not in ALLOWED_BACKGROUNDS:
|
|
269
|
+
_die("background must be one of transparent, opaque, or auto.")
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _validate_input_fidelity(input_fidelity: Optional[str]) -> None:
|
|
273
|
+
if input_fidelity not in ALLOWED_INPUT_FIDELITIES:
|
|
274
|
+
_die("input-fidelity must be one of low or high.")
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _validate_model(model: str) -> None:
|
|
278
|
+
if GPT_IMAGE_MODEL_PREFIX not in model:
|
|
279
|
+
_die(
|
|
280
|
+
"model must be a GPT Image model name containing 'gpt-image-' "
|
|
281
|
+
"(for example gpt-image-2.5-flare, gpt-image-2.5-sunburst, gpt-image-2, "
|
|
282
|
+
"gpt-image-1, or gpt-image-1-mini)."
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _is_gpt_image_2_model(model: str) -> bool:
|
|
287
|
+
return bool(re.search(r"(?:^|/)gpt-image-2(?:-\d{4}-\d{2}-\d{2})?(?:/|$)", model))
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _is_gpt_image_2_5_or_2_6_model(model: str) -> bool:
|
|
291
|
+
return bool(re.search(
|
|
292
|
+
r"(?:^|/)gpt-image-2\.(?:5|6)-(?:flare|sunburst)(?:-\d{4}-\d{2}-\d{2})?(?:/|$)",
|
|
293
|
+
model,
|
|
294
|
+
))
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _validate_transparency(background: Optional[str], output_format: str) -> None:
|
|
298
|
+
if background == "transparent" and output_format not in {"png", "webp"}:
|
|
299
|
+
_die("transparent background requires output-format png or webp.")
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _validate_model_specific_options(
|
|
303
|
+
*,
|
|
304
|
+
model: str,
|
|
305
|
+
background: Optional[str],
|
|
306
|
+
input_fidelity: Optional[str] = None,
|
|
307
|
+
) -> None:
|
|
308
|
+
if not _is_gpt_image_2_model(model):
|
|
309
|
+
return
|
|
310
|
+
if background == "transparent":
|
|
311
|
+
_die(
|
|
312
|
+
"transparent backgrounds are not supported in gpt-image-2. "
|
|
313
|
+
"Use --model gpt-image-2.5-flare --background transparent --output-format png instead."
|
|
314
|
+
)
|
|
315
|
+
if input_fidelity is not None:
|
|
316
|
+
_die(
|
|
317
|
+
"input_fidelity is not supported in gpt-image-2 because image inputs always use high fidelity for this model."
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _validate_generate_payload(payload: Dict[str, Any]) -> None:
|
|
322
|
+
model = str(payload.get("model", DEFAULT_MODEL))
|
|
323
|
+
_validate_model(model)
|
|
324
|
+
n = int(payload.get("n", 1))
|
|
325
|
+
if n < 1 or n > 10:
|
|
326
|
+
_die("n must be between 1 and 10")
|
|
327
|
+
size = str(payload.get("size", DEFAULT_SIZE))
|
|
328
|
+
quality = str(payload.get("quality", DEFAULT_QUALITY))
|
|
329
|
+
background = payload.get("background")
|
|
330
|
+
_validate_size(size, model)
|
|
331
|
+
_validate_quality(quality, model)
|
|
332
|
+
_validate_background(background)
|
|
333
|
+
_validate_model_specific_options(model=model, background=background)
|
|
334
|
+
oc = payload.get("output_compression")
|
|
335
|
+
if oc is not None and not (0 <= int(oc) <= 100):
|
|
336
|
+
_die("output_compression must be between 0 and 100")
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _build_output_paths(
|
|
340
|
+
out: str,
|
|
341
|
+
output_format: str,
|
|
342
|
+
count: int,
|
|
343
|
+
out_dir: Optional[str],
|
|
344
|
+
) -> List[Path]:
|
|
345
|
+
ext = "." + output_format
|
|
346
|
+
|
|
347
|
+
if out_dir:
|
|
348
|
+
out_base = Path(out_dir)
|
|
349
|
+
out_base.mkdir(parents=True, exist_ok=True)
|
|
350
|
+
return [out_base / f"image_{i}{ext}" for i in range(1, count + 1)]
|
|
351
|
+
|
|
352
|
+
out_path = Path(out)
|
|
353
|
+
if out_path.exists() and out_path.is_dir():
|
|
354
|
+
out_path.mkdir(parents=True, exist_ok=True)
|
|
355
|
+
return [out_path / f"image_{i}{ext}" for i in range(1, count + 1)]
|
|
356
|
+
|
|
357
|
+
if out_path.suffix == "":
|
|
358
|
+
out_path = out_path.with_suffix(ext)
|
|
359
|
+
elif output_format and out_path.suffix.lstrip(".").lower() != output_format:
|
|
360
|
+
_warn(
|
|
361
|
+
f"Output extension {out_path.suffix} does not match output-format {output_format}."
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
if count == 1:
|
|
365
|
+
return [out_path]
|
|
366
|
+
|
|
367
|
+
return [
|
|
368
|
+
out_path.with_name(f"{out_path.stem}-{i}{out_path.suffix}")
|
|
369
|
+
for i in range(1, count + 1)
|
|
370
|
+
]
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _augment_prompt(args: argparse.Namespace, prompt: str) -> str:
|
|
374
|
+
fields = _fields_from_args(args)
|
|
375
|
+
return _augment_prompt_fields(args.augment, prompt, fields)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _augment_prompt_fields(augment: bool, prompt: str, fields: Dict[str, Optional[str]]) -> str:
|
|
379
|
+
if not augment:
|
|
380
|
+
return prompt
|
|
381
|
+
|
|
382
|
+
sections: List[str] = []
|
|
383
|
+
if fields.get("use_case"):
|
|
384
|
+
sections.append(f"Use case: {fields['use_case']}")
|
|
385
|
+
sections.append(f"Primary request: {prompt}")
|
|
386
|
+
if fields.get("scene"):
|
|
387
|
+
sections.append(f"Scene/background: {fields['scene']}")
|
|
388
|
+
if fields.get("subject"):
|
|
389
|
+
sections.append(f"Subject: {fields['subject']}")
|
|
390
|
+
if fields.get("style"):
|
|
391
|
+
sections.append(f"Style/medium: {fields['style']}")
|
|
392
|
+
if fields.get("composition"):
|
|
393
|
+
sections.append(f"Composition/framing: {fields['composition']}")
|
|
394
|
+
if fields.get("lighting"):
|
|
395
|
+
sections.append(f"Lighting/mood: {fields['lighting']}")
|
|
396
|
+
if fields.get("palette"):
|
|
397
|
+
sections.append(f"Color palette: {fields['palette']}")
|
|
398
|
+
if fields.get("materials"):
|
|
399
|
+
sections.append(f"Materials/textures: {fields['materials']}")
|
|
400
|
+
if fields.get("text"):
|
|
401
|
+
sections.append(f"Text (verbatim): \"{fields['text']}\"")
|
|
402
|
+
if fields.get("constraints"):
|
|
403
|
+
sections.append(f"Constraints: {fields['constraints']}")
|
|
404
|
+
if fields.get("negative"):
|
|
405
|
+
sections.append(f"Avoid: {fields['negative']}")
|
|
406
|
+
|
|
407
|
+
return "\n".join(sections)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _fields_from_args(args: argparse.Namespace) -> Dict[str, Optional[str]]:
|
|
411
|
+
return {
|
|
412
|
+
"use_case": getattr(args, "use_case", None),
|
|
413
|
+
"scene": getattr(args, "scene", None),
|
|
414
|
+
"subject": getattr(args, "subject", None),
|
|
415
|
+
"style": getattr(args, "style", None),
|
|
416
|
+
"composition": getattr(args, "composition", None),
|
|
417
|
+
"lighting": getattr(args, "lighting", None),
|
|
418
|
+
"palette": getattr(args, "palette", None),
|
|
419
|
+
"materials": getattr(args, "materials", None),
|
|
420
|
+
"text": getattr(args, "text", None),
|
|
421
|
+
"constraints": getattr(args, "constraints", None),
|
|
422
|
+
"negative": getattr(args, "negative", None),
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _print_request(payload: dict) -> None:
|
|
427
|
+
print(json.dumps(payload, indent=2, sort_keys=True))
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _decode_and_write(images: List[str], outputs: List[Path], force: bool) -> None:
|
|
431
|
+
for idx, image_b64 in enumerate(images):
|
|
432
|
+
if idx >= len(outputs):
|
|
433
|
+
break
|
|
434
|
+
out_path = outputs[idx]
|
|
435
|
+
if out_path.exists() and not force:
|
|
436
|
+
_die(f"Output already exists: {out_path} (use --force to overwrite)")
|
|
437
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
438
|
+
out_path.write_bytes(base64.b64decode(image_b64))
|
|
439
|
+
print(f"Wrote {out_path}")
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _derive_downscale_path(path: Path, suffix: str) -> Path:
|
|
443
|
+
if suffix and not suffix.startswith("-") and not suffix.startswith("_"):
|
|
444
|
+
suffix = "-" + suffix
|
|
445
|
+
return path.with_name(f"{path.stem}{suffix}{path.suffix}")
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _downscale_image_bytes(image_bytes: bytes, *, max_dim: int, output_format: str) -> bytes:
|
|
449
|
+
try:
|
|
450
|
+
from PIL import Image
|
|
451
|
+
except Exception:
|
|
452
|
+
_die(f"Downscaling requires Pillow. {_dependency_hint('pillow')}")
|
|
453
|
+
|
|
454
|
+
if max_dim < 1:
|
|
455
|
+
_die("--downscale-max-dim must be >= 1")
|
|
456
|
+
|
|
457
|
+
with Image.open(BytesIO(image_bytes)) as img:
|
|
458
|
+
img.load()
|
|
459
|
+
w, h = img.size
|
|
460
|
+
scale = min(1.0, float(max_dim) / float(max(w, h)))
|
|
461
|
+
target = (max(1, int(round(w * scale))), max(1, int(round(h * scale))))
|
|
462
|
+
|
|
463
|
+
resized = img if target == (w, h) else img.resize(target, Image.Resampling.LANCZOS)
|
|
464
|
+
|
|
465
|
+
fmt = output_format.lower()
|
|
466
|
+
if fmt == "jpg":
|
|
467
|
+
fmt = "jpeg"
|
|
468
|
+
|
|
469
|
+
if fmt == "jpeg":
|
|
470
|
+
if resized.mode in ("RGBA", "LA") or ("transparency" in getattr(resized, "info", {})):
|
|
471
|
+
bg = Image.new("RGB", resized.size, (255, 255, 255))
|
|
472
|
+
bg.paste(resized.convert("RGBA"), mask=resized.convert("RGBA").split()[-1])
|
|
473
|
+
resized = bg
|
|
474
|
+
else:
|
|
475
|
+
resized = resized.convert("RGB")
|
|
476
|
+
|
|
477
|
+
out = BytesIO()
|
|
478
|
+
resized.save(out, format=fmt.upper())
|
|
479
|
+
return out.getvalue()
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _decode_write_and_downscale(
|
|
483
|
+
images: List[str],
|
|
484
|
+
outputs: List[Path],
|
|
485
|
+
*,
|
|
486
|
+
force: bool,
|
|
487
|
+
downscale_max_dim: Optional[int],
|
|
488
|
+
downscale_suffix: str,
|
|
489
|
+
output_format: str,
|
|
490
|
+
) -> None:
|
|
491
|
+
for idx, image_b64 in enumerate(images):
|
|
492
|
+
if idx >= len(outputs):
|
|
493
|
+
break
|
|
494
|
+
out_path = outputs[idx]
|
|
495
|
+
if out_path.exists() and not force:
|
|
496
|
+
_die(f"Output already exists: {out_path} (use --force to overwrite)")
|
|
497
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
498
|
+
|
|
499
|
+
raw = base64.b64decode(image_b64)
|
|
500
|
+
out_path.write_bytes(raw)
|
|
501
|
+
print(f"Wrote {out_path}")
|
|
502
|
+
|
|
503
|
+
if downscale_max_dim is None:
|
|
504
|
+
continue
|
|
505
|
+
|
|
506
|
+
derived = _derive_downscale_path(out_path, downscale_suffix)
|
|
507
|
+
if derived.exists() and not force:
|
|
508
|
+
_die(f"Output already exists: {derived} (use --force to overwrite)")
|
|
509
|
+
derived.parent.mkdir(parents=True, exist_ok=True)
|
|
510
|
+
resized = _downscale_image_bytes(raw, max_dim=downscale_max_dim, output_format=output_format)
|
|
511
|
+
derived.write_bytes(resized)
|
|
512
|
+
print(f"Wrote {derived}")
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def _slugify(value: str) -> str:
|
|
516
|
+
value = value.strip().lower()
|
|
517
|
+
value = re.sub(r"[^a-z0-9]+", "-", value)
|
|
518
|
+
value = re.sub(r"-{2,}", "-", value).strip("-")
|
|
519
|
+
return value[:60] if value else "job"
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def _normalize_job(job: Any, idx: int) -> Dict[str, Any]:
|
|
523
|
+
if isinstance(job, str):
|
|
524
|
+
prompt = job.strip()
|
|
525
|
+
if not prompt:
|
|
526
|
+
_die(f"Empty prompt at job {idx}")
|
|
527
|
+
return {"prompt": prompt}
|
|
528
|
+
if isinstance(job, dict):
|
|
529
|
+
if "prompt" not in job or not str(job["prompt"]).strip():
|
|
530
|
+
_die(f"Missing prompt for job {idx}")
|
|
531
|
+
return job
|
|
532
|
+
_die(f"Invalid job at index {idx}: expected string or object.")
|
|
533
|
+
return {} # unreachable
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def _read_jobs_jsonl(path: str) -> List[Dict[str, Any]]:
|
|
537
|
+
p = Path(path)
|
|
538
|
+
if not p.exists():
|
|
539
|
+
_die(f"Input file not found: {p}")
|
|
540
|
+
jobs: List[Dict[str, Any]] = []
|
|
541
|
+
for line_no, raw in enumerate(p.read_text(encoding="utf-8").splitlines(), start=1):
|
|
542
|
+
line = raw.strip()
|
|
543
|
+
if not line or line.startswith("#"):
|
|
544
|
+
continue
|
|
545
|
+
try:
|
|
546
|
+
item: Any
|
|
547
|
+
if line.startswith("{"):
|
|
548
|
+
item = json.loads(line)
|
|
549
|
+
else:
|
|
550
|
+
item = line
|
|
551
|
+
jobs.append(_normalize_job(item, idx=line_no))
|
|
552
|
+
except json.JSONDecodeError as exc:
|
|
553
|
+
_die(f"Invalid JSON on line {line_no}: {exc}")
|
|
554
|
+
if not jobs:
|
|
555
|
+
_die("No jobs found in input file.")
|
|
556
|
+
if len(jobs) > MAX_BATCH_JOBS:
|
|
557
|
+
_die(f"Too many jobs ({len(jobs)}). Max is {MAX_BATCH_JOBS}.")
|
|
558
|
+
return jobs
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _merge_non_null(dst: Dict[str, Any], src: Dict[str, Any]) -> Dict[str, Any]:
|
|
562
|
+
merged = dict(dst)
|
|
563
|
+
for k, v in src.items():
|
|
564
|
+
if v is not None:
|
|
565
|
+
merged[k] = v
|
|
566
|
+
return merged
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def _job_output_paths(
|
|
570
|
+
*,
|
|
571
|
+
out_dir: Path,
|
|
572
|
+
output_format: str,
|
|
573
|
+
idx: int,
|
|
574
|
+
prompt: str,
|
|
575
|
+
n: int,
|
|
576
|
+
explicit_out: Optional[str],
|
|
577
|
+
) -> List[Path]:
|
|
578
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
579
|
+
ext = "." + output_format
|
|
580
|
+
|
|
581
|
+
if explicit_out:
|
|
582
|
+
base = Path(explicit_out)
|
|
583
|
+
if base.suffix == "":
|
|
584
|
+
base = base.with_suffix(ext)
|
|
585
|
+
elif base.suffix.lstrip(".").lower() != output_format:
|
|
586
|
+
_warn(
|
|
587
|
+
f"Job {idx}: output extension {base.suffix} does not match output-format {output_format}."
|
|
588
|
+
)
|
|
589
|
+
base = out_dir / base.name
|
|
590
|
+
else:
|
|
591
|
+
slug = _slugify(prompt[:80])
|
|
592
|
+
base = out_dir / f"{idx:03d}-{slug}{ext}"
|
|
593
|
+
|
|
594
|
+
if n == 1:
|
|
595
|
+
return [base]
|
|
596
|
+
return [
|
|
597
|
+
base.with_name(f"{base.stem}-{i}{base.suffix}")
|
|
598
|
+
for i in range(1, n + 1)
|
|
599
|
+
]
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
async def _run_generate_batch(args: argparse.Namespace) -> int:
|
|
603
|
+
jobs = _read_jobs_jsonl(args.input)
|
|
604
|
+
out_dir = Path(args.out_dir)
|
|
605
|
+
|
|
606
|
+
base_fields = _fields_from_args(args)
|
|
607
|
+
base_payload = {
|
|
608
|
+
"model": args.model,
|
|
609
|
+
"n": args.n,
|
|
610
|
+
"size": args.size,
|
|
611
|
+
"quality": args.quality,
|
|
612
|
+
"background": args.background,
|
|
613
|
+
"output_format": args.output_format,
|
|
614
|
+
"output_compression": args.output_compression,
|
|
615
|
+
"moderation": args.moderation,
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
if args.dry_run:
|
|
619
|
+
for i, job in enumerate(jobs, start=1):
|
|
620
|
+
prompt = str(job["prompt"]).strip()
|
|
621
|
+
fields = _merge_non_null(base_fields, job.get("fields", {}))
|
|
622
|
+
# Allow flat job keys as well (use_case, scene, etc.)
|
|
623
|
+
fields = _merge_non_null(fields, {k: job.get(k) for k in base_fields.keys()})
|
|
624
|
+
augmented = _augment_prompt_fields(args.augment, prompt, fields)
|
|
625
|
+
|
|
626
|
+
job_payload = dict(base_payload)
|
|
627
|
+
job_payload["prompt"] = augmented
|
|
628
|
+
job_payload = _merge_non_null(job_payload, {k: job.get(k) for k in base_payload.keys()})
|
|
629
|
+
job_payload = {k: v for k, v in job_payload.items() if v is not None}
|
|
630
|
+
|
|
631
|
+
_validate_generate_payload(job_payload)
|
|
632
|
+
effective_output_format = _normalize_output_format(job_payload.get("output_format"))
|
|
633
|
+
_validate_transparency(job_payload.get("background"), effective_output_format)
|
|
634
|
+
job_payload["output_format"] = effective_output_format
|
|
635
|
+
|
|
636
|
+
n = int(job_payload.get("n", 1))
|
|
637
|
+
outputs = _job_output_paths(
|
|
638
|
+
out_dir=out_dir,
|
|
639
|
+
output_format=effective_output_format,
|
|
640
|
+
idx=i,
|
|
641
|
+
prompt=prompt,
|
|
642
|
+
n=n,
|
|
643
|
+
explicit_out=job.get("out"),
|
|
644
|
+
)
|
|
645
|
+
downscaled = None
|
|
646
|
+
if args.downscale_max_dim is not None:
|
|
647
|
+
downscaled = [
|
|
648
|
+
str(_derive_downscale_path(p, args.downscale_suffix)) for p in outputs
|
|
649
|
+
]
|
|
650
|
+
_print_request(
|
|
651
|
+
{
|
|
652
|
+
"endpoint": _preview_endpoint("generate"),
|
|
653
|
+
"job": i,
|
|
654
|
+
"outputs": [str(p) for p in outputs],
|
|
655
|
+
"outputs_downscaled": downscaled,
|
|
656
|
+
**{
|
|
657
|
+
**job_payload,
|
|
658
|
+
"model": _preview_model(str(job_payload["model"]), "generate"),
|
|
659
|
+
},
|
|
660
|
+
}
|
|
661
|
+
)
|
|
662
|
+
return 0
|
|
663
|
+
|
|
664
|
+
provider = create_image_provider(api_key=os.getenv("OPENAI_API_KEY"), base_url=_api_base_url())
|
|
665
|
+
sem = asyncio.Semaphore(args.concurrency)
|
|
666
|
+
|
|
667
|
+
any_failed = False
|
|
668
|
+
|
|
669
|
+
async def run_job(i: int, job: Dict[str, Any]) -> Tuple[int, Optional[str]]:
|
|
670
|
+
nonlocal any_failed
|
|
671
|
+
prompt = str(job["prompt"]).strip()
|
|
672
|
+
job_label = f"[job {i}/{len(jobs)}]"
|
|
673
|
+
|
|
674
|
+
fields = _merge_non_null(base_fields, job.get("fields", {}))
|
|
675
|
+
fields = _merge_non_null(fields, {k: job.get(k) for k in base_fields.keys()})
|
|
676
|
+
augmented = _augment_prompt_fields(args.augment, prompt, fields)
|
|
677
|
+
|
|
678
|
+
payload = dict(base_payload)
|
|
679
|
+
payload["prompt"] = augmented
|
|
680
|
+
payload = _merge_non_null(payload, {k: job.get(k) for k in base_payload.keys()})
|
|
681
|
+
payload = {k: v for k, v in payload.items() if v is not None}
|
|
682
|
+
|
|
683
|
+
n = int(payload.get("n", 1))
|
|
684
|
+
_validate_generate_payload(payload)
|
|
685
|
+
effective_output_format = _normalize_output_format(payload.get("output_format"))
|
|
686
|
+
_validate_transparency(payload.get("background"), effective_output_format)
|
|
687
|
+
payload["output_format"] = effective_output_format
|
|
688
|
+
outputs = _job_output_paths(
|
|
689
|
+
out_dir=out_dir,
|
|
690
|
+
output_format=effective_output_format,
|
|
691
|
+
idx=i,
|
|
692
|
+
prompt=prompt,
|
|
693
|
+
n=n,
|
|
694
|
+
explicit_out=job.get("out"),
|
|
695
|
+
)
|
|
696
|
+
try:
|
|
697
|
+
async with sem:
|
|
698
|
+
print(f"{job_label} starting", file=sys.stderr)
|
|
699
|
+
started = time.time()
|
|
700
|
+
images = await provider.generate_batch(
|
|
701
|
+
payload,
|
|
702
|
+
attempts=args.max_attempts,
|
|
703
|
+
job_label=job_label,
|
|
704
|
+
)
|
|
705
|
+
elapsed = time.time() - started
|
|
706
|
+
print(f"{job_label} completed in {elapsed:.1f}s", file=sys.stderr)
|
|
707
|
+
_decode_write_and_downscale(
|
|
708
|
+
images,
|
|
709
|
+
outputs,
|
|
710
|
+
force=args.force,
|
|
711
|
+
downscale_max_dim=args.downscale_max_dim,
|
|
712
|
+
downscale_suffix=args.downscale_suffix,
|
|
713
|
+
output_format=effective_output_format,
|
|
714
|
+
)
|
|
715
|
+
return i, None
|
|
716
|
+
except Exception as exc:
|
|
717
|
+
any_failed = True
|
|
718
|
+
print(f"{job_label} failed: {exc}", file=sys.stderr)
|
|
719
|
+
if args.fail_fast:
|
|
720
|
+
raise
|
|
721
|
+
return i, str(exc)
|
|
722
|
+
|
|
723
|
+
tasks = [asyncio.create_task(run_job(i, job)) for i, job in enumerate(jobs, start=1)]
|
|
724
|
+
|
|
725
|
+
try:
|
|
726
|
+
await asyncio.gather(*tasks)
|
|
727
|
+
except Exception:
|
|
728
|
+
for t in tasks:
|
|
729
|
+
if not t.done():
|
|
730
|
+
t.cancel()
|
|
731
|
+
raise
|
|
732
|
+
|
|
733
|
+
return 1 if any_failed else 0
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def _generate_batch(args: argparse.Namespace) -> None:
|
|
737
|
+
exit_code = asyncio.run(_run_generate_batch(args))
|
|
738
|
+
if exit_code:
|
|
739
|
+
raise SystemExit(exit_code)
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
def _generate(args: argparse.Namespace) -> None:
|
|
743
|
+
prompt = _read_prompt(args.prompt, args.prompt_file)
|
|
744
|
+
prompt = _augment_prompt(args, prompt)
|
|
745
|
+
|
|
746
|
+
payload = {
|
|
747
|
+
"model": args.model,
|
|
748
|
+
"prompt": prompt,
|
|
749
|
+
"n": args.n,
|
|
750
|
+
"size": args.size,
|
|
751
|
+
"quality": args.quality,
|
|
752
|
+
"background": args.background,
|
|
753
|
+
"output_format": args.output_format,
|
|
754
|
+
"output_compression": args.output_compression,
|
|
755
|
+
"moderation": args.moderation,
|
|
756
|
+
}
|
|
757
|
+
payload = {k: v for k, v in payload.items() if v is not None}
|
|
758
|
+
|
|
759
|
+
output_format = _normalize_output_format(args.output_format)
|
|
760
|
+
_validate_transparency(args.background, output_format)
|
|
761
|
+
payload["output_format"] = output_format
|
|
762
|
+
output_paths = _build_output_paths(args.out, output_format, args.n, args.out_dir)
|
|
763
|
+
downscaled = None
|
|
764
|
+
if args.downscale_max_dim is not None:
|
|
765
|
+
downscaled = [str(_derive_downscale_path(p, args.downscale_suffix)) for p in output_paths]
|
|
766
|
+
|
|
767
|
+
if args.dry_run:
|
|
768
|
+
_print_request(
|
|
769
|
+
{
|
|
770
|
+
"endpoint": _preview_endpoint("generate"),
|
|
771
|
+
"outputs": [str(p) for p in output_paths],
|
|
772
|
+
"outputs_downscaled": downscaled,
|
|
773
|
+
**{
|
|
774
|
+
**payload,
|
|
775
|
+
"model": _preview_model(str(payload["model"]), "generate"),
|
|
776
|
+
},
|
|
777
|
+
}
|
|
778
|
+
)
|
|
779
|
+
return
|
|
780
|
+
|
|
781
|
+
print(
|
|
782
|
+
"Calling Image API (generation). This can take up to a couple of minutes.",
|
|
783
|
+
file=sys.stderr,
|
|
784
|
+
)
|
|
785
|
+
started = time.time()
|
|
786
|
+
provider = create_image_provider(api_key=os.getenv("OPENAI_API_KEY"), base_url=_api_base_url())
|
|
787
|
+
images = provider.generate(payload)
|
|
788
|
+
elapsed = time.time() - started
|
|
789
|
+
print(f"Generation completed in {elapsed:.1f}s.", file=sys.stderr)
|
|
790
|
+
|
|
791
|
+
_decode_write_and_downscale(
|
|
792
|
+
images,
|
|
793
|
+
output_paths,
|
|
794
|
+
force=args.force,
|
|
795
|
+
downscale_max_dim=args.downscale_max_dim,
|
|
796
|
+
downscale_suffix=args.downscale_suffix,
|
|
797
|
+
output_format=output_format,
|
|
798
|
+
)
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def _edit(args: argparse.Namespace) -> None:
|
|
802
|
+
prompt = _read_prompt(args.prompt, args.prompt_file)
|
|
803
|
+
prompt = _augment_prompt(args, prompt)
|
|
804
|
+
|
|
805
|
+
image_paths = _check_image_paths(args.image)
|
|
806
|
+
mask_path = Path(args.mask) if args.mask else None
|
|
807
|
+
if mask_path:
|
|
808
|
+
if not mask_path.exists():
|
|
809
|
+
_die(f"Mask file not found: {mask_path}")
|
|
810
|
+
if mask_path.suffix.lower() != ".png":
|
|
811
|
+
_warn(f"Mask should be a PNG with an alpha channel: {mask_path}")
|
|
812
|
+
if mask_path.stat().st_size > MAX_IMAGE_BYTES:
|
|
813
|
+
_warn(f"Mask exceeds 50MB limit: {mask_path}")
|
|
814
|
+
|
|
815
|
+
payload = {
|
|
816
|
+
"model": args.model,
|
|
817
|
+
"prompt": prompt,
|
|
818
|
+
"n": args.n,
|
|
819
|
+
"size": args.size,
|
|
820
|
+
"quality": args.quality,
|
|
821
|
+
"background": args.background,
|
|
822
|
+
"output_format": args.output_format,
|
|
823
|
+
"output_compression": args.output_compression,
|
|
824
|
+
"input_fidelity": args.input_fidelity,
|
|
825
|
+
"moderation": args.moderation,
|
|
826
|
+
}
|
|
827
|
+
payload = {k: v for k, v in payload.items() if v is not None}
|
|
828
|
+
|
|
829
|
+
output_format = _normalize_output_format(args.output_format)
|
|
830
|
+
_validate_transparency(args.background, output_format)
|
|
831
|
+
payload["output_format"] = output_format
|
|
832
|
+
_validate_input_fidelity(args.input_fidelity)
|
|
833
|
+
output_paths = _build_output_paths(args.out, output_format, args.n, args.out_dir)
|
|
834
|
+
downscaled = None
|
|
835
|
+
if args.downscale_max_dim is not None:
|
|
836
|
+
downscaled = [str(_derive_downscale_path(p, args.downscale_suffix)) for p in output_paths]
|
|
837
|
+
|
|
838
|
+
if args.dry_run:
|
|
839
|
+
payload_preview = dict(payload)
|
|
840
|
+
payload_preview["image"] = [str(p) for p in image_paths]
|
|
841
|
+
if mask_path:
|
|
842
|
+
payload_preview["mask"] = str(mask_path)
|
|
843
|
+
_print_request(
|
|
844
|
+
{
|
|
845
|
+
"endpoint": _preview_endpoint("edit"),
|
|
846
|
+
"outputs": [str(p) for p in output_paths],
|
|
847
|
+
"outputs_downscaled": downscaled,
|
|
848
|
+
**{
|
|
849
|
+
**payload_preview,
|
|
850
|
+
"model": _preview_model(str(payload_preview["model"]), "edit"),
|
|
851
|
+
},
|
|
852
|
+
}
|
|
853
|
+
)
|
|
854
|
+
return
|
|
855
|
+
|
|
856
|
+
print(
|
|
857
|
+
f"Calling Image API (edit) with {len(image_paths)} image(s).",
|
|
858
|
+
file=sys.stderr,
|
|
859
|
+
)
|
|
860
|
+
started = time.time()
|
|
861
|
+
provider = create_image_provider(api_key=os.getenv("OPENAI_API_KEY"), base_url=_api_base_url())
|
|
862
|
+
images = provider.edit(payload, image_paths, mask_path)
|
|
863
|
+
|
|
864
|
+
elapsed = time.time() - started
|
|
865
|
+
print(f"Edit completed in {elapsed:.1f}s.", file=sys.stderr)
|
|
866
|
+
_decode_write_and_downscale(
|
|
867
|
+
images,
|
|
868
|
+
output_paths,
|
|
869
|
+
force=args.force,
|
|
870
|
+
downscale_max_dim=args.downscale_max_dim,
|
|
871
|
+
downscale_suffix=args.downscale_suffix,
|
|
872
|
+
output_format=output_format,
|
|
873
|
+
)
|
|
874
|
+
|
|
875
|
+
|
|
876
|
+
def _add_shared_args(parser: argparse.ArgumentParser) -> None:
|
|
877
|
+
parser.add_argument("--model", default=_default_model())
|
|
878
|
+
parser.add_argument("--prompt")
|
|
879
|
+
parser.add_argument("--prompt-file")
|
|
880
|
+
parser.add_argument("--n", type=int, default=1)
|
|
881
|
+
parser.add_argument("--size", default=DEFAULT_SIZE)
|
|
882
|
+
parser.add_argument("--quality", default=DEFAULT_QUALITY)
|
|
883
|
+
parser.add_argument("--background")
|
|
884
|
+
parser.add_argument("--output-format")
|
|
885
|
+
parser.add_argument("--output-compression", type=int)
|
|
886
|
+
parser.add_argument("--moderation")
|
|
887
|
+
parser.add_argument("--out", default=DEFAULT_OUTPUT_PATH)
|
|
888
|
+
parser.add_argument("--out-dir")
|
|
889
|
+
parser.add_argument("--force", action="store_true")
|
|
890
|
+
parser.add_argument("--dry-run", action="store_true")
|
|
891
|
+
parser.add_argument("--augment", dest="augment", action="store_true")
|
|
892
|
+
parser.add_argument("--no-augment", dest="augment", action="store_false")
|
|
893
|
+
parser.set_defaults(augment=True)
|
|
894
|
+
|
|
895
|
+
# Prompt augmentation hints
|
|
896
|
+
parser.add_argument("--use-case")
|
|
897
|
+
parser.add_argument("--scene")
|
|
898
|
+
parser.add_argument("--subject")
|
|
899
|
+
parser.add_argument("--style")
|
|
900
|
+
parser.add_argument("--composition")
|
|
901
|
+
parser.add_argument("--lighting")
|
|
902
|
+
parser.add_argument("--palette")
|
|
903
|
+
parser.add_argument("--materials")
|
|
904
|
+
parser.add_argument("--text")
|
|
905
|
+
parser.add_argument("--constraints")
|
|
906
|
+
parser.add_argument("--negative")
|
|
907
|
+
|
|
908
|
+
# Post-processing (optional): generate an additional downscaled copy for fast web loading.
|
|
909
|
+
parser.add_argument("--downscale-max-dim", type=int)
|
|
910
|
+
parser.add_argument("--downscale-suffix", default=DEFAULT_DOWNSCALE_SUFFIX)
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
def main() -> int:
|
|
914
|
+
_load_runtime_env()
|
|
915
|
+
parser = argparse.ArgumentParser(
|
|
916
|
+
description="Fallback CLI for explicit image generation or editing via GPT Image models"
|
|
917
|
+
)
|
|
918
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
919
|
+
|
|
920
|
+
gen_parser = subparsers.add_parser("generate", help="Create a new image")
|
|
921
|
+
_add_shared_args(gen_parser)
|
|
922
|
+
gen_parser.set_defaults(func=_generate)
|
|
923
|
+
|
|
924
|
+
batch_parser = subparsers.add_parser(
|
|
925
|
+
"generate-batch",
|
|
926
|
+
help="Generate multiple prompts concurrently (JSONL input)",
|
|
927
|
+
)
|
|
928
|
+
_add_shared_args(batch_parser)
|
|
929
|
+
batch_parser.add_argument("--input", required=True, help="Path to JSONL file (one job per line)")
|
|
930
|
+
batch_parser.add_argument("--concurrency", type=int, default=DEFAULT_CONCURRENCY)
|
|
931
|
+
batch_parser.add_argument("--max-attempts", type=int, default=3)
|
|
932
|
+
batch_parser.add_argument("--fail-fast", action="store_true")
|
|
933
|
+
batch_parser.set_defaults(func=_generate_batch)
|
|
934
|
+
|
|
935
|
+
edit_parser = subparsers.add_parser("edit", help="Edit an existing image")
|
|
936
|
+
_add_shared_args(edit_parser)
|
|
937
|
+
edit_parser.add_argument("--image", action="append", required=True)
|
|
938
|
+
edit_parser.add_argument("--mask")
|
|
939
|
+
edit_parser.add_argument("--input-fidelity")
|
|
940
|
+
edit_parser.set_defaults(func=_edit)
|
|
941
|
+
|
|
942
|
+
args = parser.parse_args()
|
|
943
|
+
if args.n < 1 or args.n > 10:
|
|
944
|
+
_die("--n must be between 1 and 10")
|
|
945
|
+
if getattr(args, "concurrency", 1) < 1 or getattr(args, "concurrency", 1) > 25:
|
|
946
|
+
_die("--concurrency must be between 1 and 25")
|
|
947
|
+
if getattr(args, "max_attempts", 3) < 1 or getattr(args, "max_attempts", 3) > 10:
|
|
948
|
+
_die("--max-attempts must be between 1 and 10")
|
|
949
|
+
if args.output_compression is not None and not (0 <= args.output_compression <= 100):
|
|
950
|
+
_die("--output-compression must be between 0 and 100")
|
|
951
|
+
if args.command == "generate-batch" and not args.out_dir:
|
|
952
|
+
_die("generate-batch requires --out-dir")
|
|
953
|
+
if getattr(args, "downscale_max_dim", None) is not None and args.downscale_max_dim < 1:
|
|
954
|
+
_die("--downscale-max-dim must be >= 1")
|
|
955
|
+
|
|
956
|
+
_validate_model(args.model)
|
|
957
|
+
_validate_size(args.size, args.model)
|
|
958
|
+
_validate_quality(args.quality, args.model)
|
|
959
|
+
_validate_background(args.background)
|
|
960
|
+
_validate_model_specific_options(
|
|
961
|
+
model=args.model,
|
|
962
|
+
background=args.background,
|
|
963
|
+
input_fidelity=getattr(args, "input_fidelity", None),
|
|
964
|
+
)
|
|
965
|
+
_ensure_api_key(args.dry_run)
|
|
966
|
+
|
|
967
|
+
args.func(args)
|
|
968
|
+
return 0
|
|
969
|
+
|
|
970
|
+
|
|
971
|
+
if __name__ == "__main__":
|
|
972
|
+
raise SystemExit(main())
|