tempest_fastapi_sdk.genai.image¶
Geração de imagem local sobre o diffusers do HuggingFace.
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
¶
Supported input image forms accepted by :meth:ImageGenerator.edit.
ImagePipelineOutput
¶
Bases: Protocol
Output object returned by a diffusers text-to-image pipeline.
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 ( |
dtype |
ModelDtypeEnum
|
The resolved compute precision. |
source |
ModelRef
|
The resolved weight identity forwarded to
|
image_format |
str
|
Encoding of the returned bytes. |
pipeline_kwargs |
dict[str, Any]
|
Extra |
idle_unload_seconds |
float | None
|
Idle threshold used by
:meth: |
Configure the generator (does not load weights yet).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
HuggingFace diffusion model id. |
required |
device
|
str
|
|
'auto'
|
dtype
|
str | ModelDtypeEnum
|
Compute precision, or |
'auto'
|
cache_dir
|
str | None
|
Where the downloaded weights are
written and read back from. |
None
|
hf_token
|
str | None
|
Hub token for gated or private
repositories. |
None
|
revision
|
str | None
|
Branch, tag or commit sha to load;
|
None
|
local_files_only
|
bool | None
|
Load from the cache without
touching the network — what an air-gapped or deploy-frozen
host wants. |
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'
|
pipeline_kwargs
|
dict[str, Any] | None
|
Extra keywords for
|
None
|
max_concurrent
|
int
|
Simultaneous renders. Defaults to |
1
|
idle_unload_seconds
|
float | None
|
When set,
:meth: |
None
|
hardware
|
HardwareInfo | None
|
Injected snapshot for device
resolution (tests); probed when |
None
|
metrics
|
GenAIMetrics | None
|
Optional Prometheus metrics;
when set, :meth: |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
is_loaded
property
¶
Return True once the pipeline is in memory.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether :meth: |
bool
|
meth: |
seconds_idle
property
¶
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
¶
pipeline: ImageDiffusionPipeline
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 |
load
¶
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 |
unload
¶
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
¶
Free the pipeline when it has been idle past the threshold.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
when it was already free, still in use, or no |
|
bool
|
|
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 |
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, |
required |
strength
|
float
|
How far to move from the input, |
0.8
|
config
|
ImageGenerationConfig | None
|
Steps, guidance, seed
and count. |
None
|
Returns:
| Type | Description |
|---|---|
list[GeneratedImage]
|
list[GeneratedImage]: The redrawn images. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
TypeError
|
When |
ValueError
|
When |