imagewright 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,36 @@
1
+ """imagewright -- image generation over one HTTP contract.
2
+
3
+ A client for ``/v1/images/generations``, local FLUX and SDXL-Lightning
4
+ servers that answer it, and an MCP tool. Nothing here depends on a knowledge
5
+ graph.
6
+ """
7
+
8
+ from importlib.metadata import version
9
+
10
+ from imagewright.client import ImageSynthesizer, MissingExtraError
11
+ from imagewright.config import ImageBackend, ImageConfig, image_config_from_env
12
+ from imagewright.discovery import (
13
+ DEFAULT_IMAGE_ENDPOINTS,
14
+ NoImageBackendError,
15
+ discover_image_endpoint,
16
+ resolve_image_config,
17
+ )
18
+ from imagewright.mcp_image import MCP_IMAGE_MAX_BYTES, as_mcp_image, compress_image
19
+
20
+ __version__ = version("imagewright")
21
+
22
+ __all__ = [
23
+ "DEFAULT_IMAGE_ENDPOINTS",
24
+ "MCP_IMAGE_MAX_BYTES",
25
+ "ImageBackend",
26
+ "ImageConfig",
27
+ "ImageSynthesizer",
28
+ "MissingExtraError",
29
+ "NoImageBackendError",
30
+ "__version__",
31
+ "as_mcp_image",
32
+ "compress_image",
33
+ "discover_image_endpoint",
34
+ "image_config_from_env",
35
+ "resolve_image_config",
36
+ ]
@@ -0,0 +1,75 @@
1
+ """Pieces both image servers share: environment parsing, extras checks and the reply body."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import importlib.util
7
+ import os
8
+ import tempfile
9
+ import time
10
+ import uuid
11
+ from io import BytesIO
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from PIL.Image import Image as PILImage
16
+
17
+ from imagewright.client import MissingExtraError
18
+
19
+ #: Modules the ``serve`` extra installs.
20
+ SERVE_MODULES: tuple[str, ...] = ("fastapi", "uvicorn", "pydantic")
21
+
22
+
23
+ def env_flag(name: str) -> bool:
24
+ """Read a yes/no environment variable.
25
+
26
+ :param name: Variable name.
27
+ :returns: True when it is ``1``, ``true`` or ``yes`` (any case, spaces ignored).
28
+ """
29
+ return os.environ.get(name, "").strip().lower() in {"1", "true", "yes"}
30
+
31
+
32
+ def env_output_dir() -> Path:
33
+ """Directory for ``response_format=filepath`` images.
34
+
35
+ :returns: ``IMAGE_OUTPUT_DIR``, else ``imagewright_images`` in the system temp directory.
36
+ """
37
+ default = Path(tempfile.gettempdir()) / "imagewright_images"
38
+ return Path(os.environ.get("IMAGE_OUTPUT_DIR") or default)
39
+
40
+
41
+ def require_modules(modules: tuple[str, ...], extras: str, what: str) -> None:
42
+ """Fail with the pip command to run when any of *modules* is not installed.
43
+
44
+ :param modules: Top-level module names to look for.
45
+ :param extras: The extras that install them, comma-separated, e.g. ``"serve,flux"``.
46
+ :param what: What needs them, for the message, e.g. ``"the FLUX server"``.
47
+ :raises MissingExtraError: Naming the missing modules and the pip command.
48
+ """
49
+ missing = [name for name in modules if importlib.util.find_spec(name) is None]
50
+ if missing:
51
+ raise MissingExtraError(
52
+ f"{', '.join(missing)} not installed; {what} needs the {extras!r} "
53
+ f'extras: pip install "imagewright[{extras}]"'
54
+ )
55
+
56
+
57
+ def image_reply(image: PILImage, response_format: str, output_dir: Path) -> dict[str, Any]:
58
+ """Build the ``/v1/images/generations`` response body.
59
+
60
+ :param image: The rendered image.
61
+ :param response_format: ``"filepath"`` writes a PNG under *output_dir* and returns its
62
+ path; anything else returns the PNG as base64 in ``b64_json``.
63
+ :param output_dir: Where ``filepath`` images go; created when missing.
64
+ :returns: ``{"created": <unix time>, "data": [{"b64_json" | "filepath": ...}]}``.
65
+ """
66
+ if response_format == "filepath":
67
+ output_dir.mkdir(parents=True, exist_ok=True)
68
+ out = output_dir / f"{uuid.uuid4().hex}.png"
69
+ image.save(str(out))
70
+ return {"created": int(time.time()), "data": [{"filepath": str(out)}]}
71
+
72
+ buf = BytesIO()
73
+ image.save(buf, format="PNG")
74
+ b64 = base64.b64encode(buf.getvalue()).decode()
75
+ return {"created": int(time.time()), "data": [{"b64_json": b64}]}
imagewright/cli.py ADDED
@@ -0,0 +1,136 @@
1
+ """The ``imagewright`` command line."""
2
+
3
+ import os
4
+ import warnings
5
+ from datetime import datetime
6
+ from pathlib import Path
7
+
8
+ import click
9
+ import httpx
10
+
11
+ from imagewright import __version__
12
+ from imagewright.client import ImageSynthesizer, MissingExtraError, _parse_size
13
+ from imagewright.config import ImageBackend
14
+ from imagewright.discovery import NoImageBackendError, resolve_image_config
15
+
16
+
17
+ @click.group()
18
+ @click.version_option(__version__, prog_name="imagewright")
19
+ def cli() -> None:
20
+ """Generate images through a local server, an in-process model or OpenAI."""
21
+
22
+
23
+ @cli.command()
24
+ @click.argument("prompt")
25
+ @click.option("--size", metavar="WxH", help="Output size, e.g. 1536x1024 (default 3:2).")
26
+ @click.option("--seed", type=int, help="Random seed for a reproducible image.")
27
+ @click.option("--steps", type=int, help="Inference steps (FLUX backends; default 4).")
28
+ @click.option(
29
+ "--backend",
30
+ type=click.Choice([b.value for b in ImageBackend]),
31
+ help="Backend to use. Default: IMAGE_BACKEND, else a server found locally, "
32
+ "else in-process FLUX if installed.",
33
+ )
34
+ @click.option("--endpoint", metavar="URL", help="Image server base URL (implies mflux-serve).")
35
+ @click.option(
36
+ "-o",
37
+ "--output",
38
+ type=click.Path(dir_okay=False, path_type=Path),
39
+ help="PNG path to write. Default: imagewright-YYYYMMDD-HHMMSS.png here.",
40
+ )
41
+ def generate(
42
+ prompt: str,
43
+ size: str | None,
44
+ seed: int | None,
45
+ steps: int | None,
46
+ backend: str | None,
47
+ endpoint: str | None,
48
+ output: Path | None,
49
+ ) -> None:
50
+ """Generate an image from PROMPT, write it as a PNG and print its path.
51
+
52
+ \f
53
+ :param prompt: Text description of the image.
54
+ :param size: ``WIDTHxHEIGHT``, or None for the 3:2 default.
55
+ :param seed: Random seed, or None for a random one.
56
+ :param steps: Inference steps, or None for the configured default.
57
+ :param backend: Backend name, or None to choose one automatically.
58
+ :param endpoint: Image server base URL, or None.
59
+ :param output: Where to write the PNG, or None for a timestamped name.
60
+ """
61
+ if size is not None and _parse_size(size) is None:
62
+ raise click.BadParameter(f"{size!r} is not WIDTHxHEIGHT", param_hint="--size")
63
+ with warnings.catch_warnings(record=True) as caught:
64
+ warnings.simplefilter("always")
65
+ try:
66
+ config = resolve_image_config(backend, endpoint)
67
+ except (NoImageBackendError, ValueError) as exc:
68
+ raise click.ClickException(str(exc)) from exc
69
+ for w in caught:
70
+ click.echo(f"warning: {w.message}", err=True)
71
+ try:
72
+ image = ImageSynthesizer(config).generate(prompt, size=size, seed=seed, steps=steps)
73
+ except MissingExtraError as exc:
74
+ raise click.ClickException(str(exc)) from exc
75
+ except httpx.HTTPError as exc:
76
+ raise click.ClickException(
77
+ f"image server {config.resolved_server_url()} failed: {exc}"
78
+ ) from exc
79
+
80
+ path = output or Path(f"imagewright-{datetime.now():%Y%m%d-%H%M%S}.png")
81
+ image.save(path, format="PNG")
82
+ click.echo(str(path))
83
+
84
+
85
+ @cli.command()
86
+ @click.option(
87
+ "--backend",
88
+ type=click.Choice(["flux", "sdxl"]),
89
+ default="flux",
90
+ show_default=True,
91
+ help="flux: FLUX.2 Klein through mflux (Apple Silicon). sdxl: SDXL-Lightning "
92
+ "through diffusers (CUDA, MPS or CPU).",
93
+ )
94
+ @click.option(
95
+ "--host",
96
+ help="Address to bind. Default: MFLUX_SERVER_HOST (SDXL_SERVER_HOST for sdxl), "
97
+ "else 127.0.0.1. The server has no authentication; bind 0.0.0.0 only on a "
98
+ "network you trust.",
99
+ )
100
+ @click.option(
101
+ "--port",
102
+ type=click.IntRange(0, 65535),
103
+ help="Port to bind. Default: MFLUX_SERVER_PORT (SDXL_SERVER_PORT for sdxl), "
104
+ "else 8090 (8091 for sdxl).",
105
+ )
106
+ def serve(backend: str, host: str | None, port: int | None) -> None:
107
+ """Run an image server that answers /v1/images/generations.
108
+
109
+ The FLUX server needs the serve and flux extras; the SDXL server needs serve
110
+ and sdxl.
111
+
112
+ \f
113
+ :param backend: ``flux`` or ``sdxl``.
114
+ :param host: Bind address, or None for the environment or 127.0.0.1.
115
+ :param port: Bind port, or None for the environment or the backend's default.
116
+ """
117
+ if backend == "flux":
118
+ from imagewright import flux_server as server # noqa: PLC0415 - only `serve` needs it
119
+
120
+ env_prefix = "MFLUX_SERVER"
121
+ else:
122
+ from imagewright import sdxl_server as server # noqa: PLC0415 - only `serve` needs it
123
+
124
+ env_prefix = "SDXL_SERVER"
125
+ try:
126
+ server.require_extras()
127
+ except MissingExtraError as exc:
128
+ raise click.ClickException(str(exc)) from exc
129
+
130
+ host = host or os.environ.get(f"{env_prefix}_HOST") or "127.0.0.1"
131
+ if port is None:
132
+ port = int(os.environ.get(f"{env_prefix}_PORT") or server.DEFAULT_PORT)
133
+
134
+ import uvicorn # noqa: PLC0415 - the `serve` extra
135
+
136
+ uvicorn.run(server.create_app(), host=host, port=port)
imagewright/client.py ADDED
@@ -0,0 +1,387 @@
1
+ """ImageSynthesizer: image generation across mflux-local, mflux-serve and OpenAI.
2
+
3
+ Only httpx and pillow are imported here at module scope. The model stacks
4
+ (mflux, mlx, openai) are imported inside the method that needs them, so a
5
+ core install imports this module, and a backend whose extra is missing raises
6
+ :class:`MissingExtraError` naming the extra to install.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import gc
13
+ import importlib
14
+ import os
15
+ import random
16
+ from collections.abc import Callable
17
+ from concurrent.futures import ThreadPoolExecutor
18
+ from io import BytesIO
19
+ from types import ModuleType
20
+ from typing import Any
21
+
22
+ import httpx
23
+ from PIL import Image
24
+ from PIL.Image import Image as PILImage
25
+
26
+ from imagewright.config import ImageBackend, ImageConfig
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Aspect-ratio -> pixel dimension tables
30
+ # ---------------------------------------------------------------------------
31
+
32
+ # Used by mflux backends (arbitrary resolution).
33
+ _MFLUX_SIZES: dict[str, tuple[int, int]] = {
34
+ "1:1": (1024, 1024),
35
+ "3:2": (1536, 1024),
36
+ "2:3": (1024, 1536),
37
+ "16:9": (1536, 864),
38
+ "9:16": (864, 1536),
39
+ "4:3": (1365, 1024),
40
+ "3:4": (1024, 1365),
41
+ }
42
+
43
+ # DALL-E 3 only supports three sizes; map aspect ratios to the nearest valid option.
44
+ _DALLE3_SIZES: dict[str, str] = {
45
+ "1:1": "1024x1024",
46
+ "3:2": "1792x1024",
47
+ "2:3": "1024x1792",
48
+ "16:9": "1792x1024",
49
+ "9:16": "1024x1792",
50
+ "4:3": "1792x1024",
51
+ "3:4": "1024x1792",
52
+ }
53
+
54
+ # gpt-image-1 supports portrait/landscape 1024x1536 instead of 1792-wide.
55
+ _GPT_IMAGE_SIZES: dict[str, str] = {
56
+ "1:1": "1024x1024",
57
+ "3:2": "1536x1024",
58
+ "2:3": "1024x1536",
59
+ "16:9": "1536x1024",
60
+ "9:16": "1024x1536",
61
+ "4:3": "1536x1024",
62
+ "3:4": "1024x1536",
63
+ }
64
+
65
+ _FLUX2_KLEIN_MODULE = "mflux.models.flux2.variants.txt2img.flux2_klein"
66
+
67
+
68
+ class MissingExtraError(ImportError):
69
+ """A backend needs an optional extra that is not installed.
70
+
71
+ Subclasses ImportError so existing ``except ImportError`` handlers still
72
+ catch it; the message names the ``pip install`` command that fixes it.
73
+ """
74
+
75
+
76
+ def _import_extra(module: str, extra: str) -> ModuleType:
77
+ """Import *module*, or raise :class:`MissingExtraError` naming *extra*.
78
+
79
+ :param module: Dotted module name, e.g. ``"openai"``.
80
+ :param extra: The imagewright extra that installs it, e.g. ``"openai"``.
81
+ :returns: The imported module.
82
+ :raises MissingExtraError: When the module's top-level package is not installed.
83
+ """
84
+ try:
85
+ return importlib.import_module(module)
86
+ except ModuleNotFoundError as exc:
87
+ if (exc.name or "").split(".")[0] != module.split(".")[0]:
88
+ raise
89
+ raise MissingExtraError(
90
+ f"{module.split('.')[0]} is not installed; this backend needs the "
91
+ f'{extra!r} extra: pip install "imagewright[{extra}]"'
92
+ ) from exc
93
+
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # Size parsing
97
+ # ---------------------------------------------------------------------------
98
+
99
+
100
+ def _parse_size(size: str | None) -> tuple[int, int] | None:
101
+ """Parse an explicit ``"WIDTHxHEIGHT"`` string into an ``(width, height)`` pair.
102
+
103
+ :param size: Size string such as ``"768x512"`` (case-insensitive ``x``), or None.
104
+ :returns: ``(width, height)`` when *size* parses to two positive ints, else None.
105
+ """
106
+ if not size:
107
+ return None
108
+ try:
109
+ w_str, h_str = size.lower().split("x", 1)
110
+ width, height = int(w_str), int(h_str)
111
+ except (ValueError, AttributeError):
112
+ return None
113
+ if width <= 0 or height <= 0:
114
+ return None
115
+ return width, height
116
+
117
+
118
+ # ---------------------------------------------------------------------------
119
+ # Synthesizer
120
+ # ---------------------------------------------------------------------------
121
+
122
+
123
+ class ImageSynthesizer:
124
+ """Unified image generation across mflux-local, mflux-serve and OpenAI.
125
+
126
+ All ``generate*`` methods return a PIL ``Image``; callers that need a base64
127
+ string (e.g. HTTP wire responses) should use ``generate_b64()``. A
128
+ per-instance mflux model cache avoids reloading across calls to the same
129
+ synthesizer; :meth:`unload_model` releases it.
130
+
131
+ :param config: Backend configuration produced by ``image_config_from_env()``,
132
+ ``resolve_image_config()``, or built directly as an ``ImageConfig``.
133
+ """
134
+
135
+ def __init__(self, config: ImageConfig) -> None:
136
+ self._cfg = config
137
+ self._mflux_model: Any = None
138
+ self._mflux_model_name: str | None = None
139
+ # One worker; it starts no thread until the in-process model is first used.
140
+ self._model_thread = ThreadPoolExecutor(
141
+ max_workers=1, thread_name_prefix="imagewright-flux"
142
+ )
143
+
144
+ # ------------------------------------------------------------------
145
+ # In-process model lifecycle
146
+ # ------------------------------------------------------------------
147
+
148
+ def _on_model_thread[T](self, fn: Callable[..., T], *args: Any, **kwargs: Any) -> T:
149
+ """Run *fn* on this synthesizer's one model thread and return its result.
150
+
151
+ MLX ties a model to the thread that loaded it: a render on any other
152
+ thread fails with "There is no Stream(cpu, 0) in current thread". So the
153
+ load, every render and the unload all run on one thread, whichever
154
+ thread the caller is on. A server that preloads at startup and renders
155
+ in a worker thread depends on this.
156
+
157
+ :param fn: The model operation.
158
+ :returns: What *fn* returns; an exception it raises is raised here.
159
+ """
160
+ return self._model_thread.submit(fn, *args, **kwargs).result()
161
+
162
+ def _load_mflux(self, model_name: str) -> Any:
163
+ if self._mflux_model is not None and self._mflux_model_name == model_name:
164
+ return self._mflux_model
165
+
166
+ Flux2Klein = _import_extra(_FLUX2_KLEIN_MODULE, "flux").Flux2Klein
167
+
168
+ self._mflux_model = Flux2Klein(model_path=model_name)
169
+ self._mflux_model_name = model_name
170
+ return self._mflux_model
171
+
172
+ def load_model(self) -> None:
173
+ """Load the in-process Flux2Klein model now instead of on the first render.
174
+
175
+ An image server calls this to preload. A no-op when the configured model
176
+ is already loaded.
177
+
178
+ :raises MissingExtraError: When the ``flux`` extra is not installed.
179
+ """
180
+ self._on_model_thread(self._load_mflux, self._cfg.resolved_model())
181
+
182
+ @property
183
+ def model_loaded(self) -> bool:
184
+ """``True`` while an in-process Flux2Klein model is held in memory."""
185
+ return self._mflux_model is not None
186
+
187
+ def unload_model(self) -> bool:
188
+ """Drop the cached Flux2Klein model and return its memory to the system.
189
+
190
+ An image server calls this after its idle timeout, so a small Mac gets
191
+ FLUX's 12-15 GB back. The next in-process generation loads the model again.
192
+
193
+ :returns: ``True`` if a model was unloaded, ``False`` if none was loaded.
194
+ """
195
+ return self._on_model_thread(self._unload_mflux)
196
+
197
+ def _unload_mflux(self) -> bool:
198
+ if self._mflux_model is None:
199
+ return False
200
+ self._mflux_model = None
201
+ self._mflux_model_name = None
202
+ gc.collect()
203
+ try:
204
+ mx = importlib.import_module("mlx.core")
205
+ clear = getattr(mx, "clear_cache", None) or mx.metal.clear_cache
206
+ clear()
207
+ except (ImportError, AttributeError):
208
+ pass
209
+ return True
210
+
211
+ # ------------------------------------------------------------------
212
+ # Public API
213
+ # ------------------------------------------------------------------
214
+
215
+ def generate(
216
+ self,
217
+ prompt: str,
218
+ *,
219
+ aspect_ratio: str = "3:2",
220
+ seed: int | None = None,
221
+ steps: int | None = None,
222
+ model: str | None = None,
223
+ size: str | None = None,
224
+ ) -> PILImage:
225
+ """Generate an image and return a PIL Image.
226
+
227
+ :param prompt: Text description of the scene to generate.
228
+ :param aspect_ratio: One of 1:1, 3:2, 2:3, 16:9, 9:16, 4:3, 3:4.
229
+ :param seed: Random seed for reproducibility (random int if omitted).
230
+ :param steps: Override inference steps (mflux backends only; ignored for OpenAI).
231
+ :param model: Override the configured model for this single call.
232
+ :param size: Explicit ``"WIDTHxHEIGHT"`` override (mflux backends only). When given
233
+ and valid, it takes priority over the *aspect_ratio* size table. OpenAI
234
+ backends ignore it because they accept only a fixed set of sizes.
235
+ :returns: PIL Image.
236
+ :raises MissingExtraError: When the backend's extra is not installed.
237
+ """
238
+ cfg = self._cfg
239
+ effective_steps = steps if steps is not None else cfg.steps
240
+ effective_model = model or cfg.resolved_model()
241
+
242
+ if cfg.backend == ImageBackend.MFLUX_LOCAL:
243
+ return self._on_model_thread(
244
+ self._generate_local,
245
+ prompt,
246
+ model=effective_model,
247
+ seed=seed,
248
+ steps=effective_steps,
249
+ aspect_ratio=aspect_ratio,
250
+ size=size,
251
+ )
252
+ elif cfg.backend == ImageBackend.MFLUX_SERVE:
253
+ return self._generate_via_server(
254
+ prompt,
255
+ server_url=cfg.resolved_server_url(),
256
+ seed=seed,
257
+ steps=effective_steps,
258
+ aspect_ratio=aspect_ratio,
259
+ size=size,
260
+ )
261
+ else:
262
+ return self._generate_openai(
263
+ prompt,
264
+ model=effective_model,
265
+ aspect_ratio=aspect_ratio,
266
+ )
267
+
268
+ def generate_b64(
269
+ self,
270
+ prompt: str,
271
+ *,
272
+ aspect_ratio: str = "3:2",
273
+ seed: int | None = None,
274
+ steps: int | None = None,
275
+ model: str | None = None,
276
+ size: str | None = None,
277
+ ) -> str:
278
+ """Generate an image and return it as a base64-encoded PNG string.
279
+
280
+ Convenience wrapper around ``generate()`` for HTTP wire responses.
281
+
282
+ :param prompt: Text description of the scene to generate.
283
+ :param aspect_ratio: One of 1:1, 3:2, 2:3, 16:9, 9:16, 4:3, 3:4.
284
+ :param seed: Random seed for reproducibility.
285
+ :param steps: Override inference steps (mflux backends only).
286
+ :param model: Override the configured model for this single call.
287
+ :param size: Explicit ``"WIDTHxHEIGHT"`` override (mflux backends only).
288
+ :returns: Base64-encoded PNG string.
289
+ """
290
+ img = self.generate(
291
+ prompt, aspect_ratio=aspect_ratio, seed=seed, steps=steps, model=model, size=size
292
+ )
293
+ buf = BytesIO()
294
+ img.save(buf, format="PNG")
295
+ return base64.b64encode(buf.getvalue()).decode()
296
+
297
+ # ------------------------------------------------------------------
298
+ # Backend implementations
299
+ # ------------------------------------------------------------------
300
+
301
+ def _generate_local(
302
+ self,
303
+ prompt: str,
304
+ *,
305
+ model: str,
306
+ seed: int | None,
307
+ steps: int,
308
+ aspect_ratio: str,
309
+ size: str | None = None,
310
+ ) -> PILImage:
311
+ width, height = _parse_size(size) or _MFLUX_SIZES.get(aspect_ratio, _MFLUX_SIZES["3:2"])
312
+ effective_seed = seed if seed is not None else random.randint(0, 2**31 - 1)
313
+ flux = self._load_mflux(model)
314
+ result = flux.generate_image(
315
+ seed=effective_seed,
316
+ prompt=prompt,
317
+ width=width,
318
+ height=height,
319
+ guidance=1.0,
320
+ num_inference_steps=steps,
321
+ scheduler="flow_match_euler_discrete",
322
+ )
323
+ return result.image
324
+
325
+ def _generate_via_server(
326
+ self,
327
+ prompt: str,
328
+ *,
329
+ server_url: str,
330
+ seed: int | None,
331
+ steps: int,
332
+ aspect_ratio: str,
333
+ size: str | None = None,
334
+ ) -> PILImage:
335
+ width, height = _parse_size(size) or _MFLUX_SIZES.get(aspect_ratio, _MFLUX_SIZES["3:2"])
336
+ payload: dict[str, Any] = {
337
+ "prompt": prompt,
338
+ "n": 1,
339
+ "size": f"{width}x{height}",
340
+ "num_inference_steps": steps,
341
+ "response_format": "b64_json",
342
+ }
343
+ if seed is not None:
344
+ payload["seed"] = seed
345
+
346
+ resp = httpx.post(
347
+ server_url.rstrip("/") + "/v1/images/generations",
348
+ json=payload,
349
+ timeout=httpx.Timeout(connect=5.0, read=300.0, write=10.0, pool=5.0),
350
+ )
351
+ resp.raise_for_status()
352
+ b64 = resp.json()["data"][0]["b64_json"]
353
+ return Image.open(BytesIO(base64.b64decode(b64)))
354
+
355
+ def _generate_openai(
356
+ self,
357
+ prompt: str,
358
+ *,
359
+ model: str,
360
+ aspect_ratio: str,
361
+ ) -> PILImage:
362
+ OpenAI = _import_extra("openai", "openai").OpenAI
363
+
364
+ cfg = self._cfg
365
+ api_key = cfg.api_key or os.environ.get("OPENAI_API_KEY", "")
366
+
367
+ # gpt-image-1 uses different valid sizes and does not accept response_format.
368
+ # dall-e-3 returns a URL by default; gpt-image-1 returns b64_json by default.
369
+ if model.startswith("gpt-image"):
370
+ size = _GPT_IMAGE_SIZES.get(aspect_ratio, _GPT_IMAGE_SIZES["3:2"])
371
+ else:
372
+ size = _DALLE3_SIZES.get(aspect_ratio, _DALLE3_SIZES["3:2"])
373
+
374
+ client = OpenAI(api_key=api_key)
375
+ resp = client.images.generate(
376
+ model=model,
377
+ prompt=prompt,
378
+ n=1,
379
+ size=size,
380
+ )
381
+ item = resp.data[0] if resp.data else None
382
+ if item and item.b64_json:
383
+ return Image.open(BytesIO(base64.b64decode(item.b64_json)))
384
+ if item and item.url:
385
+ raw = httpx.get(item.url, timeout=httpx.Timeout(30.0)).content
386
+ return Image.open(BytesIO(raw))
387
+ raise RuntimeError("OpenAI image response contained neither b64_json nor url")