Skip to content

Client (imagewright.client)

imagewright.client

ImageSynthesizer: image generation across mflux-local, mflux-serve and OpenAI.

Only httpx and pillow are imported here at module scope. The model stacks (mflux, mlx, openai) are imported inside the method that needs them, so a core install imports this module, and a backend whose extra is missing raises :class:MissingExtraError naming the extra to install.

ImageSynthesizer(config)

Unified image generation across mflux-local, mflux-serve and OpenAI.

All generate* methods return a PIL Image; callers that need a base64 string (e.g. HTTP wire responses) should use generate_b64(). A per-instance mflux model cache avoids reloading across calls to the same synthesizer; :meth:unload_model releases it.

Parameters:

Name Type Description Default
config ImageConfig

Backend configuration produced by image_config_from_env(), resolve_image_config(), or built directly as an ImageConfig.

required
Source code in src/imagewright/client.py
135
136
137
138
139
140
141
142
def __init__(self, config: ImageConfig) -> None:
    self._cfg = config
    self._mflux_model: Any = None
    self._mflux_model_name: str | None = None
    # One worker; it starts no thread until the in-process model is first used.
    self._model_thread = ThreadPoolExecutor(
        max_workers=1, thread_name_prefix="imagewright-flux"
    )

model_loaded property

True while an in-process Flux2Klein model is held in memory.

generate(prompt, *, aspect_ratio='3:2', seed=None, steps=None, model=None, size=None)

Generate an image and return a PIL Image.

Parameters:

Name Type Description Default
prompt str

Text description of the scene to generate.

required
aspect_ratio str

One of 1:1, 3:2, 2:3, 16:9, 9:16, 4:3, 3:4.

'3:2'
seed int | None

Random seed for reproducibility (random int if omitted).

None
steps int | None

Override inference steps (mflux backends only; ignored for OpenAI).

None
model str | None

Override the configured model for this single call.

None
size str | None

Explicit "WIDTHxHEIGHT" override (mflux backends only). When given and valid, it takes priority over the aspect_ratio size table. OpenAI backends ignore it because they accept only a fixed set of sizes.

None

Returns:

Type Description
Image

PIL Image.

Raises:

Type Description
MissingExtraError

When the backend's extra is not installed.

Source code in src/imagewright/client.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
def generate(
    self,
    prompt: str,
    *,
    aspect_ratio: str = "3:2",
    seed: int | None = None,
    steps: int | None = None,
    model: str | None = None,
    size: str | None = None,
) -> PILImage:
    """Generate an image and return a PIL Image.

    :param prompt: Text description of the scene to generate.
    :param aspect_ratio: One of 1:1, 3:2, 2:3, 16:9, 9:16, 4:3, 3:4.
    :param seed: Random seed for reproducibility (random int if omitted).
    :param steps: Override inference steps (mflux backends only; ignored for OpenAI).
    :param model: Override the configured model for this single call.
    :param size: Explicit ``"WIDTHxHEIGHT"`` override (mflux backends only). When given
                 and valid, it takes priority over the *aspect_ratio* size table. OpenAI
                 backends ignore it because they accept only a fixed set of sizes.
    :returns: PIL Image.
    :raises MissingExtraError: When the backend's extra is not installed.
    """
    cfg = self._cfg
    effective_steps = steps if steps is not None else cfg.steps
    effective_model = model or cfg.resolved_model()

    if cfg.backend == ImageBackend.MFLUX_LOCAL:
        return self._on_model_thread(
            self._generate_local,
            prompt,
            model=effective_model,
            seed=seed,
            steps=effective_steps,
            aspect_ratio=aspect_ratio,
            size=size,
        )
    elif cfg.backend == ImageBackend.MFLUX_SERVE:
        return self._generate_via_server(
            prompt,
            server_url=cfg.resolved_server_url(),
            seed=seed,
            steps=effective_steps,
            aspect_ratio=aspect_ratio,
            size=size,
        )
    else:
        return self._generate_openai(
            prompt,
            model=effective_model,
            aspect_ratio=aspect_ratio,
        )

generate_b64(prompt, *, aspect_ratio='3:2', seed=None, steps=None, model=None, size=None)

Generate an image and return it as a base64-encoded PNG string.

Convenience wrapper around generate() for HTTP wire responses.

Parameters:

Name Type Description Default
prompt str

Text description of the scene to generate.

required
aspect_ratio str

One of 1:1, 3:2, 2:3, 16:9, 9:16, 4:3, 3:4.

'3:2'
seed int | None

Random seed for reproducibility.

None
steps int | None

Override inference steps (mflux backends only).

None
model str | None

Override the configured model for this single call.

None
size str | None

Explicit "WIDTHxHEIGHT" override (mflux backends only).

None

Returns:

Type Description
str

Base64-encoded PNG string.

Source code in src/imagewright/client.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def generate_b64(
    self,
    prompt: str,
    *,
    aspect_ratio: str = "3:2",
    seed: int | None = None,
    steps: int | None = None,
    model: str | None = None,
    size: str | None = None,
) -> str:
    """Generate an image and return it as a base64-encoded PNG string.

    Convenience wrapper around ``generate()`` for HTTP wire responses.

    :param prompt: Text description of the scene to generate.
    :param aspect_ratio: One of 1:1, 3:2, 2:3, 16:9, 9:16, 4:3, 3:4.
    :param seed: Random seed for reproducibility.
    :param steps: Override inference steps (mflux backends only).
    :param model: Override the configured model for this single call.
    :param size: Explicit ``"WIDTHxHEIGHT"`` override (mflux backends only).
    :returns: Base64-encoded PNG string.
    """
    img = self.generate(
        prompt, aspect_ratio=aspect_ratio, seed=seed, steps=steps, model=model, size=size
    )
    buf = BytesIO()
    img.save(buf, format="PNG")
    return base64.b64encode(buf.getvalue()).decode()

load_model()

Load the in-process Flux2Klein model now instead of on the first render.

An image server calls this to preload. A no-op when the configured model is already loaded.

Raises:

Type Description
MissingExtraError

When the flux extra is not installed.

Source code in src/imagewright/client.py
172
173
174
175
176
177
178
179
180
def load_model(self) -> None:
    """Load the in-process Flux2Klein model now instead of on the first render.

    An image server calls this to preload. A no-op when the configured model
    is already loaded.

    :raises MissingExtraError: When the ``flux`` extra is not installed.
    """
    self._on_model_thread(self._load_mflux, self._cfg.resolved_model())

unload_model()

Drop the cached Flux2Klein model and return its memory to the system.

An image server calls this after its idle timeout, so a small Mac gets FLUX's 12-15 GB back. The next in-process generation loads the model again.

Returns:

Type Description
bool

True if a model was unloaded, False if none was loaded.

Source code in src/imagewright/client.py
187
188
189
190
191
192
193
194
195
def unload_model(self) -> bool:
    """Drop the cached Flux2Klein model and return its memory to the system.

    An image server calls this after its idle timeout, so a small Mac gets
    FLUX's 12-15 GB back. The next in-process generation loads the model again.

    :returns: ``True`` if a model was unloaded, ``False`` if none was loaded.
    """
    return self._on_model_thread(self._unload_mflux)

MissingExtraError

Bases: ImportError

A backend needs an optional extra that is not installed.

Subclasses ImportError so existing except ImportError handlers still catch it; the message names the pip install command that fixes it.