Ir para o conteúdo

tempest_fastapi_sdk.genai.image

Geração de imagem local sobre o diffusers do HuggingFace.

« IA e visão computacional


image

Local image generation over HuggingFace diffusers.

ImageGenerator loads a diffusion pipeline once and renders on your own hardware. It mirrors :class:~tempest_fastapi_sdk.genai.TextGenerator — same device/precision resolution, same lazy load, same idle unload, same Hub pinning keywords — so a service that already self-hosts a language model gains images without learning a second set of conventions.

Two operations, one loaded pipeline: :meth:ImageGenerator.generate (text to image) and :meth:ImageGenerator.edit (image to image). The second is built with AutoPipelineForImage2Image.from_pipe, which reuses the already-loaded components instead of allocating a second copy of the weights — an SDXL pipeline is ~7 GB, and loading it twice on one card is how a service OOMs at the first edit request.

diffusers and torch are imported inside :meth:ImageGenerator.load, so this module imports without the [genai-image] extra.

Concurrency defaults to one render at a time. Unlike a language model, a diffusion pipeline saturates the GPU on a single call; running two concurrently makes both slower and doubles peak VRAM.

ImageSource

ImageSource = str | Path | bytes | bytearray | Image | NDArray[Any]

Supported input image forms accepted by :meth:ImageGenerator.edit.

ImagePipelineOutput

Bases: Protocol

Output object returned by a diffusers text-to-image pipeline.

images property

images: Sequence[Any]

Generated images, one per requested sample.

ImageDiffusionPipeline

Bases: Protocol

Minimal surface of a loaded diffusers image pipeline.

ImageGenerator

ImageGenerator(
    model_id: str,
    *,
    device: str = "auto",
    dtype: str | ModelDtypeEnum = "auto",
    cache_dir: str | None = None,
    hf_token: str | None = None,
    revision: str | None = None,
    local_files_only: bool | None = None,
    trust_remote_code: bool = False,
    image_format: str = "png",
    pipeline_kwargs: dict[str, Any] | None = None,
    max_concurrent: int = 1,
    idle_unload_seconds: float | None = None,
    hardware: HardwareInfo | None = None,
    metrics: GenAIMetrics | None = None,
)

A lazily-loaded local diffusion pipeline with idle unload.

Example:

>>> gen = ImageGenerator("stabilityai/sdxl-turbo")
>>> images = await gen.generate(
...     "a lighthouse at dawn",
...     config=ImageGenerationConfig(steps=4, guidance_scale=0.0),
... )
>>> Path("out.png").write_bytes(images[0].data)
>>> gen.unload()

Attributes:

Name Type Description
model_id str

The HuggingFace model id.

device str

The resolved device (cuda / mps / cpu).

dtype ModelDtypeEnum

The resolved compute precision.

source ModelRef

The resolved weight identity forwarded to from_pretrained.

image_format str

Encoding of the returned bytes.

pipeline_kwargs dict[str, Any]

Extra from_pretrained keywords, applied last so they override what the SDK computes.

idle_unload_seconds float | None

Idle threshold used by :meth:unload_if_idle.

Configure the generator (does not load weights yet).

Parameters:

Name Type Description Default
model_id str

HuggingFace diffusion model id.

required
device str

"auto" / "cuda" / "mps" / "cpu".

'auto'
dtype str | ModelDtypeEnum

Compute precision, or "auto" (bf16 on GPU, fp32 on CPU).

'auto'
cache_dir str | None

Where the downloaded weights are written and read back from. None uses the huggingface_hub default — $HF_HOME/hub, or ~/.cache/huggingface/hub when HF_HOME is unset — which is why the second run of a script starts instantly instead of downloading again. Point it at a mounted volume when the process is a container, so the layer does not re-download the model on every restart.

None
hf_token str | None

Hub token for gated or private repositories. None falls back to HF_TOKEN in the environment; without either, anonymous downloads work but are rate-limited (the Hub says so on stderr).

None
revision str | None

Branch, tag or commit sha to load; None follows the moving Hub default.

None
local_files_only bool | None

Load from the cache without touching the network — what an air-gapped or deploy-frozen host wants. None (the default) takes GENAI_OFFLINE from the environment; passing the argument overrides it.

None
trust_remote_code bool

Allow the repository's own Python to run at load time.

False
image_format str

Encoding of the returned bytes — "png" (lossless, the default), "jpeg" or "webp".

'png'
pipeline_kwargs dict[str, Any] | None

Extra keywords for from_pretrained, for the load-time decisions the SDK does not model. The three that come up constantly: {"safety_checker": None} skips the extra CLIP that Stable Diffusion 1.x repositories bundle (it costs memory and can blank an image); {"variant": "fp16"} fetches the half-precision weights, roughly halving the download; {"use_safetensors": True} refuses a pickle checkpoint. Keys here win over the ones the SDK computes, so this is also the way to override torch_dtype.

None
max_concurrent int

Simultaneous renders. Defaults to 1 because one diffusion call already saturates the GPU.

1
idle_unload_seconds float | None

When set, :meth:unload_if_idle frees the pipeline after this many idle seconds.

None
hardware HardwareInfo | None

Injected snapshot for device resolution (tests); probed when None.

None
metrics GenAIMetrics | None

Optional Prometheus metrics; when set, :meth:generate / :meth:edit record request count and latency (op "image" / "image_edit").

None

Raises:

Type Description
ValueError

When max_concurrent is not positive.

is_loaded property

is_loaded: bool

Return True once the pipeline is in memory.

Returns:

Name Type Description
bool bool

Whether :meth:load has run without a later

bool

meth:unload.

seconds_idle property

seconds_idle: float

Return seconds since the pipeline was last in use.

A render in flight counts as use for its whole duration, so this reads 0.0 while one runs.

Returns:

Name Type Description
float float

Idle time in seconds.

pipeline property

Return the underlying diffusers pipeline (escape hatch).

Use it to swap the scheduler, attach a LoRA or enable a memory optimization the SDK does not wrap. Loads on first access, which blocks for the whole download and build.

Returns:

Name Type Description
ImageDiffusionPipeline ImageDiffusionPipeline

The loaded AutoPipelineForText2Image.

load

load() -> None

Download (if needed) and load the diffusion pipeline.

Idempotent — a no-op once loaded. Called automatically by :meth:generate / :meth:edit, on their worker thread. Safe to call from several threads at once: concurrent callers on a cold instance wait for one build.

Raises:

Type Description
ImportError

When the [genai-image] extra is missing.

unload

unload() -> None

Free the pipeline and its memory (VRAM/RAM).

Safe to call when not loaded. After this, the next render reloads the weights. While renders are in flight the release waits for them: the last one to finish drops the pipeline.

unload_if_idle

unload_if_idle() -> bool

Free the pipeline when it has been idle past the threshold.

Returns:

Name Type Description
bool bool

True when this call unloaded the pipeline, False

bool

when it was already free, still in use, or no

bool

idle_unload_seconds was configured.

generate async

generate(
    prompt: str, *, config: ImageGenerationConfig | None = None
) -> list[GeneratedImage]

Render one or more images from a text prompt.

Runs the blocking pipeline — including the first-call load — in a worker thread, capped by the concurrency semaphore, so it never blocks the event loop.

Example:

>>> images = await generator.generate("a red bicycle")
>>> images[0].seed
418223901

Parameters:

Name Type Description Default
prompt str

What to draw.

required
config ImageGenerationConfig | None

Size, steps, guidance, seed and count. Unset fields fall through to the model's own defaults, which differ by an order of magnitude between a turbo model and a full one.

None

Returns:

Type Description
list[GeneratedImage]

list[GeneratedImage]: The rendered images, each carrying the

list[GeneratedImage]

seed that reproduces it.

Raises:

Type Description
ImportError

When the [genai-image] extra is missing.

edit async

edit(
    prompt: str,
    image: ImageSource,
    *,
    strength: float = 0.8,
    config: ImageGenerationConfig | None = None,
) -> list[GeneratedImage]

Redraw an existing image under a new prompt (image-to-image).

The load, the image-to-image pipeline build and the decoding of image all run on the worker thread with the render, so none of them blocks the event loop.

Example:

>>> edited = await generator.edit(
...     "the same room, at night",
...     "room.png",
...     strength=0.6,
... )

Parameters:

Name Type Description Default
prompt str

What the result should depict.

required
image ImageSource

The starting image — a path, bytes, a PIL.Image or a NumPy array.

required
strength float

How far to move from the input, 0..1. Low values keep the composition; 1.0 ignores the input almost entirely.

0.8
config ImageGenerationConfig | None

Steps, guidance, seed and count. width/height are usually left unset here — the input image sets the size.

None

Returns:

Type Description
list[GeneratedImage]

list[GeneratedImage]: The redrawn images.

Raises:

Type Description
ImportError

When the [genai-image] extra is missing.

TypeError

When image is not a supported source type.

ValueError

When strength is outside 0..1.