Skip to content

FLUX server (imagewright.flux_server)

imagewright.flux_server

FLUX.2 Klein image server: the /v1/images/generations contract over an in-process model.

A FastAPI app around one long-lived :class:~imagewright.client.ImageSynthesizer in mflux-local mode, so the model stays loaded between requests. It answers the same routes, request fields and response bodies as gutenberg_kg's serve/image_server.py, so a client of that server can point here unchanged.

Run it with imagewright serve. It needs the serve and flux extras; nothing at module scope imports either, so this module imports on a core install.

Environment variables

FluxServer.from_env reads these.

IMAGE_MODEL HF repo for Flux2Klein. Fallback: GUTENKG_IMAGE_MODEL. Default: mlx-community/flux2-klein-4b-4bit IMAGE_STEPS Default inference steps (default: 4) IMAGE_OUTPUT_DIR Where response_format=filepath images go (default: imagewright_images in the system temp directory) IMAGE_PRELOAD 1/true/yes loads the model before the server accepts requests IMAGE_IDLE_UNLOAD_S Unload FLUX after this many idle seconds, so a small Mac gets its 12-15 GB back; the next render reloads it. 0 (default) keeps it loaded.

FluxServer(*, model_name=_DEFAULT_MODEL, steps=4, output_dir=None, preload=False, idle_unload_s=0)

The model, the render lock and the idle clock behind the FLUX app.

One render runs at a time, and the model is never unloaded in the middle of one: :meth:render and :meth:maybe_unload share one lock.

Parameters:

Name Type Description Default
model_name str

HF repo for Flux2Klein.

_DEFAULT_MODEL
steps int

Inference steps when a request does not set them.

4
output_dir Path | None

Where response_format=filepath images go.

None
preload bool

Load the model when the app starts, before it accepts requests.

False
idle_unload_s int

Unload the model after this many idle seconds; 0 never does.

0
Source code in src/imagewright/flux_server.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def __init__(
    self,
    *,
    model_name: str = _DEFAULT_MODEL,
    steps: int = 4,
    output_dir: Path | None = None,
    preload: bool = False,
    idle_unload_s: int = 0,
) -> None:
    self.model_name = model_name
    self.steps = steps
    self.output_dir = output_dir or env_output_dir()
    self.preload = preload
    self.idle_unload_s = idle_unload_s
    self.synth = ImageSynthesizer(
        ImageConfig(backend=ImageBackend.MFLUX_LOCAL, model=model_name, steps=steps)
    )
    self.lock = threading.Lock()
    self.last_used = time.monotonic()

from_env() classmethod

Build a server from the environment variables in the module docstring.

Returns:

Type Description
FluxServer

The configured server.

Source code in src/imagewright/flux_server.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
@classmethod
def from_env(cls) -> "FluxServer":
    """Build a server from the environment variables in the module docstring.

    :returns: The configured server.
    """
    return cls(
        model_name=os.environ.get("IMAGE_MODEL")
        or os.environ.get("GUTENKG_IMAGE_MODEL")
        or _DEFAULT_MODEL,
        steps=int(os.environ.get("IMAGE_STEPS") or 4),
        output_dir=env_output_dir(),
        preload=env_flag("IMAGE_PRELOAD"),
        idle_unload_s=int(os.environ.get("IMAGE_IDLE_UNLOAD_S") or 0),
    )

load()

Load the model now, under the render lock.

Source code in src/imagewright/flux_server.py
109
110
111
112
def load(self) -> None:
    """Load the model now, under the render lock."""
    with self.lock:
        self.synth.load_model()

maybe_unload(now=None)

Unload the model if it has been idle for idle_unload_s seconds.

Skipped while a render holds the lock; the watcher tries again later.

Parameters:

Name Type Description Default
now float | None

The current time.monotonic() reading (for tests).

None

Returns:

Type Description
bool

True if the model was unloaded.

Source code in src/imagewright/flux_server.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def maybe_unload(self, now: float | None = None) -> bool:
    """Unload the model if it has been idle for ``idle_unload_s`` seconds.

    Skipped while a render holds the lock; the watcher tries again later.

    :param now: The current ``time.monotonic()`` reading (for tests).
    :returns: ``True`` if the model was unloaded.
    """
    if self.idle_unload_s <= 0 or not self.synth.model_loaded:
        return False
    now = time.monotonic() if now is None else now
    if now - self.last_used < self.idle_unload_s:
        return False
    if not self.lock.acquire(blocking=False):
        return False
    try:
        return self.synth.unload_model()
    finally:
        self.lock.release()

render(prompt, size, seed, steps)

Render one image under the lock and note when it finished.

Parameters:

Name Type Description Default
prompt str

Text description of the image.

required
size str

"WIDTHxHEIGHT"; one that does not parse gives 1536x1024.

required
seed int | None

Random seed, or None for a random one.

required
steps int | None

Inference steps; None or 0 uses the server default.

required

Returns:

Type Description
Image

The rendered image.

Source code in src/imagewright/flux_server.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def render(self, prompt: str, size: str, seed: int | None, steps: int | None) -> PILImage:
    """Render one image under the lock and note when it finished.

    :param prompt: Text description of the image.
    :param size: ``"WIDTHxHEIGHT"``; one that does not parse gives 1536x1024.
    :param seed: Random seed, or None for a random one.
    :param steps: Inference steps; None or 0 uses the server default.
    :returns: The rendered image.
    """
    with self.lock:
        try:
            return self.synth.generate(prompt, size=size, seed=seed, steps=steps or self.steps)
        finally:
            self.last_used = time.monotonic()

watch_idle(stop, interval=None)

Check for an idle model every few seconds until stop is set.

Parameters:

Name Type Description Default
stop Event

Set it to end the loop.

required
interval float | None

Seconds between checks. Default: a quarter of idle_unload_s, kept between 5 and 30.

None
Source code in src/imagewright/flux_server.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def watch_idle(self, stop: threading.Event, interval: float | None = None) -> None:
    """Check for an idle model every few seconds until *stop* is set.

    :param stop: Set it to end the loop.
    :param interval: Seconds between checks. Default: a quarter of
        ``idle_unload_s``, kept between 5 and 30.
    """
    if interval is None:
        interval = max(5.0, min(30.0, self.idle_unload_s / 4))
    while not stop.wait(interval):
        if self.maybe_unload():
            print(
                f"[idle] FLUX unloaded after {self.idle_unload_s}s idle; "
                "the next render reloads it",
                flush=True,
            )

create_app(server=None, *, watch_interval=None)

Build the FastAPI app.

On startup the app loads the model when server.preload is set, and starts the idle watcher when server.idle_unload_s is above 0; shutdown stops it. app.state.server is server.

Parameters:

Name Type Description Default
server FluxServer | None

The model and its settings. Default: :meth:FluxServer.from_env.

None
watch_interval float | None

Seconds between idle checks (for tests); see :meth:FluxServer.watch_idle.

None

Returns:

Type Description
Any

A fastapi.FastAPI app.

Source code in src/imagewright/flux_server.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
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
def create_app(server: FluxServer | None = None, *, watch_interval: float | None = None) -> Any:
    """Build the FastAPI app.

    On startup the app loads the model when ``server.preload`` is set, and starts
    the idle watcher when ``server.idle_unload_s`` is above 0; shutdown stops it.
    ``app.state.server`` is *server*.

    :param server: The model and its settings. Default: :meth:`FluxServer.from_env`.
    :param watch_interval: Seconds between idle checks (for tests); see
        :meth:`FluxServer.watch_idle`.
    :returns: A ``fastapi.FastAPI`` app.
    """
    from fastapi import FastAPI  # noqa: PLC0415 - the `serve` extra
    from pydantic import BaseModel  # noqa: PLC0415 - the `serve` extra

    srv = server or FluxServer.from_env()

    @asynccontextmanager
    async def lifespan(_app: FastAPI) -> AsyncGenerator[None]:
        if srv.preload:
            print(f"[startup] loading model {srv.model_name} ...", flush=True)
            srv.load()
            print("[startup] model ready", flush=True)
        else:
            print(
                "[startup] IMAGE_PRELOAD disabled; model will load on first generation request",
                flush=True,
            )
        stop = threading.Event()
        watcher = None
        if srv.idle_unload_s > 0:
            watcher = threading.Thread(
                target=srv.watch_idle,
                args=(stop, watch_interval),
                name="flux-idle-unload",
                daemon=True,
            )
            watcher.start()
            print(
                f"[startup] FLUX unloads after {srv.idle_unload_s}s idle (IMAGE_IDLE_UNLOAD_S)",
                flush=True,
            )
        try:
            yield
        finally:
            stop.set()
            if watcher is not None:
                watcher.join()

    app = FastAPI(title="imagewright FLUX image server", lifespan=lifespan)
    app.state.server = srv

    class ImageGenRequest(BaseModel):
        model: str = SERVED_MODEL_ID
        prompt: str
        n: int = 1
        size: str = "1536x1024"
        quality: str | None = None
        num_inference_steps: int | None = None
        seed: int | None = None
        response_format: str = "b64_json"

    @app.get("/health")
    def health():
        """Liveness probe.

        Deliberately does no model work: it answers while a generation is in
        flight and before any weights are resident, so a caller can tell "this
        port is mine" apart from "this port is ready to be fast".
        """
        return {
            "status": "ok",
            "backend": "flux",
            "model": SERVED_MODEL_ID,
            "loaded": srv.synth.model_loaded,
            "idle_unload_s": srv.idle_unload_s,
        }

    @app.get("/v1/models")
    def list_models():
        """List the single model this server serves, in OpenAI-compatible format."""
        return {
            "object": "list",
            "data": [{"id": SERVED_MODEL_ID, "object": "model", "owned_by": "mflux"}],
        }

    @app.post("/v1/images/generations")
    async def generate_image(req: ImageGenRequest):
        """Render in a worker thread and return the image as base64 or a file path."""
        image = await asyncio.to_thread(
            srv.render, req.prompt, req.size, req.seed, req.num_inference_steps
        )
        return image_reply(image, req.response_format, srv.output_dir)

    return app

require_extras()

Check that the FLUX server can run here.

Raises:

Type Description
MissingExtraError

Naming pip install "imagewright[serve,flux]".

Source code in src/imagewright/flux_server.py
52
53
54
55
56
57
def require_extras() -> None:
    """Check that the FLUX server can run here.

    :raises MissingExtraError: Naming ``pip install "imagewright[serve,flux]"``.
    """
    _require_modules((*SERVE_MODULES, "mflux"), "serve,flux", "the FLUX server")